1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
|
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <unistd.h>
double getCPUUsage() {
std::ifstream statFile("/proc/stat");
if (!statFile) {
std::cerr << "Failed to open /proc/stat." << std::endl;
return 0.0;
}
std::string line;
std::getline(statFile, line); // 读取第一行,即总体 CPU 统计信息
std::istringstream iss(line);
std::string cpuLabel;
unsigned long long user, nice, system, idle, iowait, irq, softirq, steal, guest, guest_nice;
iss >> cpuLabel >> user >> nice >> system >> idle >> iowait >> irq >> softirq >> steal >> guest >> guest_nice;
unsigned long long totalTime = user + nice + system + idle + iowait + irq + softirq + steal;
unsigned long long totalIdle = idle + iowait;
// 等待一段时间以获取下一个时间戳
sleep(1); // 可根据需要调整时间间隔
statFile.seekg(std::ios_base::beg); // 将文件指针返回开头,准备读取下一个时间戳的数据
std::getline(statFile, line); // 再次读取第一行,即新的 CPU 统计信息
std::istringstream iss2(line);
std::string cpuLabel2;
unsigned long long user2, nice2, system2, idle2, iowait2, irq2, softirq2, steal2, guest2, guest_nice2;
iss2 >> cpuLabel2 >> user2 >> nice2 >> system2 >> idle2 >> iowait2 >> irq2 >> softirq2 >> steal2 >> guest2 >> guest_nice2;
unsigned long long totalTime2 = user2 + nice2 + system2 + idle2 + iowait2 + irq2 + softirq2 + steal2;
unsigned long long totalIdle2 = idle2 + iowait2;
// 计算 CPU 使用率
double usagePercentage = static_cast<double>(totalTime2 - totalTime) / (totalTime2 + totalIdle2 - totalTime - totalIdle) * 100.0;
return usagePercentage;
}
|