查找快速进程的CPU使用情况

Find CPU usage of a fast process

本文关键字:用情 情况 CPU 进程 查找      更新时间:2023-10-16

我正在寻找一种方法来测量1秒内完成的进程的CPU使用率。

由于速度太快,top无法做到公正。据我所知,top会拍摄快照,因此该过程可以在更新之间完成。

这个程序是用C++编写的,我在Linux上运行。若有一些简单的代码可以复制并粘贴到程序中,在main()结束时打印出CPU使用情况,那个就可以了。或者,如果有一些评测工具,我也可以使用它。

编辑-人们似乎对我想要的东西有一些误解。

我不是在寻找持续时间。我知道持续时间。大约1秒。我想知道的是CPU的使用情况。如果它是100%,那么这意味着我的CPU运行了整整1秒。

如果是50%,则表示CPU有50%的时间处于空闲状态。它有可能在等待IO——另外50%。

如果我的程序运行很长一段时间,top是好的,因为它显示了类似的东西

%Cpu(s): 0.6 us, 0.3 sy, 0.0 ni, 99.1 id, 0.0 wa, 0.0 hi, 0.0 si, 0.0 st

这意味着我的cpu有0.6%的时间处于用户空间,0.3%的时间处于内核空间,99.1%的时间处于空闲状态。

但是,正如我之前所说,top不适用于快速流程。那么我该怎么办呢?

感谢

试试这个:

#include <unistd.h>
#include <fstream>
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <boost/lexical_cast.hpp>
#include <boost/regex.hpp>
#include <boost/date_time.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>

//This function reads /proc/stat and returns the idle value for each cpu in a vector
std::vector<long long> get_idle() {
//Virtual file, created by the Linux kernel on demand
std::ifstream in( "/proc/stat" );
std::vector<long long> result;
//This might broke if there are not 8 columns in /proc/stat
boost::regex reg("cpu(\d+) (\d+) (\d+) (\d+) (\d+) (\d+) (\d+) (\d+) (\d+)");
std::string line;
while ( std::getline(in, line) ) {
boost::smatch match;
if ( boost::regex_match( line, match, reg ) ) {
long long idle_time = boost::lexical_cast<long long>(match[5]);
result.push_back( idle_time );
}

}
return result;
}
//This function returns the avarege load in the next interval_seconds for each cpu in a vector
//get_load() halts this thread for interval_seconds
std::vector<float> get_load(unsigned interval_seconds) {
boost::posix_time::ptime current_time_1 = boost::date_time::microsec_clock<boost::posix_time::ptime>::universal_time();
std::vector<long long> idle_time_1 = get_idle();
sleep(interval_seconds);
boost::posix_time::ptime current_time_2 = boost::date_time::microsec_clock<boost::posix_time::ptime>::universal_time();
std::vector<long long> idle_time_2 = get_idle();
//We have to measure the time, beacuse sleep is not accurate
const float total_seconds_elpased = float((current_time_2 - current_time_1).total_milliseconds()) / 1000.f;
std::vector<float> cpu_loads;
for ( unsigned i = 0; i < idle_time_1.size(); ++i ) {
//This might get slightly negative, because our time measurment is not accurate
const float load = 1.f - float(idle_time_2[i] - idle_time_1[i])/(100.f * total_seconds_elpased);
cpu_loads.push_back( load );
}
return cpu_loads;
}
int main() {
const unsigned measurement_count = 5;
const unsigned interval_seconds = 5;
for ( unsigned i = 0; i < measurement_count; ++i ) {
std::vector<float> cpu_loads = get_load(interval_seconds);
for ( unsigned i = 0; i < cpu_loads.size(); ++i ) {
std::cout << "cpu " << i << " : " << cpu_loads[i] * 100.f << "%" << std::endl;
}
}

return 0;
}
相关文章: