linux C++ 不延时获取CPU占用率
时间: 2023-10-19 08:19:24 浏览: 143
在Linux系统中,可以通过读取/proc/stat文件来获取CPU的使用情况,并计算出CPU的占用率。以下是一个不需要延时获取CPU占用率的C++代码示例:
```
#include <iostream>
#include <fstream>
#include <sstream>
#include <stdlib.h>
#include <unistd.h>
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 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 - Idle) / (double)Total;
return CPU_Percentage;
}
int main()
{
while (true) {
cout << "CPU usage: " << GetCPULoad() * 100 << "%" << endl;
usleep(1000000); // sleep for 1 second
}
return 0;
}
```
该代码会每秒钟输出一次CPU使用率。使用usleep函数实现在不延时的情况下获取CPU占用率。你可以根据需要修改输出内容和时间间隔。
阅读全文