[英]Find CPU usage of a fast process
我正在寻找一种方法来衡量在1秒内完成的进程的CPU使用率。
由于速度如此之快, top
不能做到公平。 据我了解, top
拍摄快照,因此可以在两次更新之间完成此过程。
该程序是C ++,我正在Linux上运行。 如果有一些简单的代码可以复制并粘贴到程序中,该代码可以在main()
末尾打印出CPU使用情况,那就可以了。 或者,如果有一些分析工具,我也可以使用。
编辑-似乎人们对我想要的东西有些误解。
我不是在找时间。 我知道持续时间。 大约1秒钟。 我想知道的是CPU使用率。 如果是100%,则表示我的CPU运行了整整1秒钟。
如果是50%,则意味着CPU有50%的时间处于空闲状态。 它可能正在等待其他50%的IO。
如果我的程序运行了很长时间,则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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.