linux C++ CPU使用率
时间: 2023-07-11 15:21:00 浏览: 59
获取Linux系统的CPU使用率可以通过读取/proc/stat文件来获取,然后使用简单的数学公式计算CPU使用率。以下是获取CPU使用率的C++代码示例:
```
#include <iostream>
#include <fstream>
#include <sstream>
#include <thread>
#include <chrono>
using namespace std;
double GetCPULoad()
{
ifstream proc_stat("/proc/stat");
string line;
getline(proc_stat, line);
istringstream iss(line);
string cpu;
long long user, nice, sys, idle, iowait, irq, softirq, steal, guest, guest_nice;
iss >> cpu >> user >> nice >> sys >> idle >> iowait >> irq >> softirq >> steal >> guest >> guest_nice;
long long PrevIdle = idle + iowait;
long long PrevNonIdle = user + nice + sys + irq + softirq + steal;
long long PrevTotal = PrevIdle + PrevNonIdle;
this_thread::sleep_for(chrono::milliseconds(100)); // sleep for a short time to get the current CPU usage
proc_stat.seekg(0);
getline(proc_stat, line);
istringstream iss2(line);
iss2 >> cpu >> user >> nice >> sys >> idle >> iowait >> irq >> softirq >> steal >> guest >> guest_nice;
long long Idle = idle + iowait;
long long NonIdle = user + nice + sys + irq + softirq + steal;
long long Total = Idle + NonIdle;
// calculate CPU usage percentage
double CPU_Percentage = (double)(Total - PrevTotal) / (double)(Total - PrevTotal + PrevIdle - Idle);
return CPU_Percentage;
}
int main()
{
// print CPU usage percentage every second
while (true) {
cout << "CPU usage: " << GetCPULoad() * 100 << "%" << endl;
this_thread::sleep_for(chrono::seconds(1));
}
return 0;
}
```
该代码会每秒钟输出一次CPU使用率。你可以根据需要修改输出内容和时间间隔。