linux下C++获取CPU总使用率
时间: 2023-09-15 10:19:39 浏览: 186
你可以使用Linux下的/proc文件系统来获取CPU总使用率。其中,/proc/stat文件提供了当前系统的CPU使用情况,包括总CPU时间、空闲CPU时间、用户CPU时间、系统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使用率。你可以根据需要修改输出内容和时间间隔。
阅读全文