如何在Linux上编写一段程序使CPU在一定程度上忙碌



我正在考虑编写一个测试工具,用于使CPU在Linux上的指定级别繁忙,例如80%的使用率。我该怎么做呢?无论这个工具是脚本还是c++程序都无关紧要。

你可以使用压力程序。你也可以使用cpuburn套件,在Ubuntu(或Debian):

apt-get install cpuburn

对于与平台无关的解决方案,您可以编译并运行这个c++ 11程序的一个或多个实例,并使用命令行参数对所需的CPU使用百分比进行微调。

//
// Application to sleep for nanoseconds specified by command-line argument
//
#include <chrono>
#include <iostream>
#include <limits>
#include <sstream>
#include <thread>
int main(int argc, char* argv[]){
  if (argc >= 2) {
    std::istringstream iss(argv[1]);
    unsigned int interval;
    if (iss >> interval)
      for(uint64_t i=0; i<std::numeric_limits<uint64_t>::max(); i++)
      std::this_thread::sleep_for(std::chrono::nanoseconds(interval));
  }
}

最新更新