linux C++获取cpu使用率、内存使用率
时间: 2023-09-09 11:08:05 浏览: 200
在Linux系统中,获取CPU使用率和内存使用率可以通过读取/proc/stat和/proc/meminfo文件来实现。下面是Linux平台下获取CPU使用率和内存使用率的示例代码:
获取CPU使用率:
```c++
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
#include <unistd.h>
using namespace std;
double getCpuUsage() {
static unsigned long long lastTotalUser, lastTotalUserLow, lastTotalSys, lastTotalIdle;
ifstream fileStat("/proc/stat");
string line;
getline(fileStat, line);
istringstream ss(line);
ss.ignore(5); // skip "cpu" word
unsigned long long totalUser, totalUserLow, totalSys, totalIdle, totalIOwait, totalIRQ, totalSoftIRQ;
ss >> totalUser >> totalUserLow >> totalSys >> totalIdle >> totalIOwait >> totalIRQ >> totalSoftIRQ;
if (totalUser < lastTotalUser || totalUserLow < lastTotalUserLow || totalSys < lastTotalSys || totalIdle < lastTotalIdle) {
// Overflow detection. Just skip this value.
return -1.0;
}
unsigned long long total = totalUser - lastTotalUser + totalUserLow - lastTotalUserLow + totalSys - lastTotalSys;
double cpuUsage = total;
total += totalIdle - lastTotalIdle;
cpuUsage /= total;
lastTotalUser = totalUser;
lastTotalUserLow = totalUserLow;
lastTotalSys = totalSys;
lastTotalIdle = totalIdle;
return cpuUsage * 100.0;
}
int main() {
while (true) {
double cpuUsage = getCpuUsage();
cout << "CPU usage: " << cpuUsage << "%" << endl;
usleep(1000000);
}
return 0;
}
```
获取内存使用率:
```c++
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
#include <unistd.h>
using namespace std;
double getMemoryUsage() {
ifstream fileMem("/proc/meminfo");
string line;
getline(fileMem, line);
istringstream ss(line);
ss.ignore(256, ' ');
unsigned long long totalMem;
ss >> totalMem;
totalMem *= 1024; // convert to bytes
getline(fileMem, line);
ss.str(line);
ss.clear();
ss.ignore(256, ' ');
unsigned long long freeMem;
ss >> freeMem;
freeMem *= 1024;
double memoryUsage = 100.0 * (totalMem - freeMem) / totalMem;
return memoryUsage;
}
int main() {
while (true) {
double memoryUsage = getMemoryUsage();
cout << "Memory usage: " << memoryUsage << "%" << endl;
usleep(1000000);
}
return 0;
}
```
以上示例代码只是提供了一个简单的思路,实际应用中还需要对获取到的数据进行处理和显示。另外,Linux系统提供了更为底层的API函数,如getrusage()和sysinfo()等,也可以用于获取系统资源使用情况。
阅读全文