使用c语言实时获取linux系统CPU各个核心的使用率
时间: 2024-03-27 14:39:42 浏览: 14
可以使用Linux系统提供的 /proc/stat 文件来获取CPU各个核心的使用率。具体方法如下:
1. 打开 /proc/stat 文件,读取其中的数据。
2. 在 /proc/stat 文件中,CPU的使用情况被记录在以 "cpu" 开头的一行中,每个核心对应一行。
3. 每行中的数据由多个字段组成,其中第一个字段为 "cpu" 或 "cpu0"、"cpu1" 等,表示对应的核心。
4. 第二个字段到第五个字段分别表示该核心从系统启动到当前时刻所经过的时间(以时钟滴答为单位)及该时间内的 CPU 使用情况。
5. 通过对比两次读取的 /proc/stat 文件中的数据,可以计算出 CPU 的使用率。
以下是一个简单的示例程序,实时输出 CPU 各个核心的使用率:
```c
#include <stdio.h>
#include <string.h>
#include <unistd.h>
int main()
{
unsigned long long last_total[64] = {0};
unsigned long long last_idle[64] = {0};
unsigned long long total[64] = {0};
unsigned long long idle[64] = {0};
float usage[64] = {0};
int cores = 0;
FILE *fp = fopen("/proc/stat", "r");
char buf[256];
while (fgets(buf, sizeof(buf), fp)) {
if (strncmp(buf, "cpu", 3) == 0) {
int index = 0;
sscanf(buf, "cpu%d %llu %llu %llu %llu", &index, &total[index], &total[index+1], &total[index+2], &total[index+3]);
if (index == 0) {
idle[index] = total[index+3];
} else {
idle[index] = total[index+3] - last_total[index+3];
}
usage[index] = 100.0 * (1.0 - (idle[index] - last_idle[index]) / (total[index] - last_total[index]));
last_total[index] = total[index];
last_idle[index] = idle[index];
cores = index + 1;
}
}
fclose(fp);
while (1) {
fp = fopen("/proc/stat", "r");
while (fgets(buf, sizeof(buf), fp)) {
if (strncmp(buf, "cpu", 3) == 0) {
int index = 0;
sscanf(buf, "cpu%d %llu %llu %llu %llu", &index, &total[index], &total[index+1], &total[index+2], &total[index+3]);
if (index == 0) {
idle[index] = total[index+3];
} else {
idle[index] = total[index+3] - last_total[index+3];
}
usage[index] = 100.0 * (1.0 - (idle[index] - last_idle[index]) / (total[index] - last_total[index]));
last_total[index] = total[index];
last_idle[index] = idle[index];
}
}
fclose(fp);
printf("CPU usage:\n");
for (int i = 0; i < cores; i++) {
printf("Core %d: %.2f%%\n", i, usage[i]);
}
printf("\n");
sleep(1);
}
return 0;
}
```
注意,以上程序只是一个简单示例,实际应用中可能需要进行更加复杂的数据处理和计算,以得到更准确的 CPU 使用率信息。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)