轮询式系统CPU占用率代碼實現
时间: 2023-11-18 21:49:14 浏览: 34
以下是一个简单的轮询式系统CPU占用率的代码实现,使用了C++编程语言:
#include <iostream>
#include <fstream>
#include <string>
#include <chrono>
#include <thread>
using namespace std;
int main()
{
int pid = getpid();
double prev_idle_time = 0, prev_total_time = 0;
while(true)
{
string path = "/proc/" + to_string(pid) + "/stat";
ifstream stat_file(path.c_str());
if(stat_file.is_open())
{
string line;
getline(stat_file, line);
stat_file.close();
size_t start_pos = line.find("(") + 1;
size_t end_pos = line.find(")");
string name = line.substr(start_pos, end_pos - start_pos);
start_pos = line.find(" ", end_pos) + 1;
end_pos = line.find(" ", start_pos);
long utime = stol(line.substr(start_pos, end_pos - start_pos));
start_pos = end_pos + 1;
end_pos = line.find(" ", start_pos);
long stime = stol(line.substr(start_pos, end_pos - start_pos));
start_pos = end_pos + 1;
end_pos = line.find(" ", start_pos);
long cutime = stol(line.substr(start_pos, end_pos - start_pos));
start_pos = end_pos + 1;
end_pos = line.find(" ", start_pos);
long cstime = stol(line.substr(start_pos, end_pos - start_pos));
start_pos = end_pos + 1;
end_pos = line.find(" ", start_pos);
long long starttime = stol(line.substr(start_pos, end_pos - start_pos));
long hertz = sysconf(_SC_CLK_TCK);
double total_time = utime + stime + cutime + cstime;
double seconds = chrono::duration_cast<chrono::duration<double>>(chrono::system_clock::now().time_since_epoch()).count();
double uptime_seconds;
ifstream uptime_file("/proc/uptime");
if(uptime_file.is_open())
{
uptime_file >> uptime_seconds;
uptime_file.close();
}
double idle_time = uptime_seconds - (starttime / hertz);
double cpu_usage = (total_time - prev_total_time) / (seconds - prev_idle_time) * 100.0;
cout << "Process " << pid << " (" << name << ") CPU usage: " << cpu_usage << "%" << endl;
prev_total_time = total_time;
prev_idle_time = seconds;
}
this_thread::sleep_for(chrono::milliseconds(1000));
}
return 0;
}
该程序使用了Linux操作系统特有的/proc文件系统来读取进程的状态信息,计算出CPU占用率。其中,主要的计算过程是根据进程的utime、stime、cutime、cstime和starttime等参数,以及系统的时钟滴答数hertz和当前时间等信息,计算出当前进程的总CPU占用时间和空闲时间,从而计算出CPU占用率。程序使用了一个死循环来不断地获取进程状态信息,并输出CPU占用率。为了避免程序过于频繁地访问/proc文件系统,导致系统资源过度消耗,程序使用了一个1秒钟的等待时间来控制轮询频率。