使用c语言实时获取linux系统CPU各个核心的使用率
时间: 2024-03-27 22:39:27 浏览: 22
可以使用Linux系统提供的/proc/stat文件来获取CPU各个核心的使用率。C语言中可以使用fopen()函数打开/proc/stat文件,然后使用fgets()函数读取文件中的内容,再使用sscanf()函数解析出CPU各个核心的使用率。
以下是一个获取CPU各个核心使用率的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_CORES 32
int main()
{
FILE* fp;
char buffer[1024];
char* token;
long double stats[MAX_CORES][10];
int num_cores = 0;
fp = fopen("/proc/stat", "r");
if (fp == NULL) {
perror("Failed to open /proc/stat");
return 1;
}
// Read the first line of /proc/stat to get the total CPU usage
fgets(buffer, sizeof(buffer), fp);
sscanf(buffer, "cpu %Lf %Lf %Lf %Lf %Lf %Lf %Lf %Lf %Lf %Lf",
&stats[0][0], &stats[0][1], &stats[0][2], &stats[0][3],
&stats[0][4], &stats[0][5], &stats[0][6], &stats[0][7],
&stats[0][8], &stats[0][9]);
// Read the rest of the lines to get the per-core CPU usage
while (fgets(buffer, sizeof(buffer), fp)) {
if (strncmp(buffer, "cpu", 3) != 0) {
// This line corresponds to a CPU core
token = strtok(buffer, " ");
token = strtok(NULL, " ");
for (int i = 0; i < 10; i++) {
token = strtok(NULL, " ");
stats[num_cores+1][i] = strtold(token, NULL);
}
num_cores++;
}
}
fclose(fp);
// Print the CPU usage for each core
for (int i = 0; i <= num_cores; i++) {
printf("Core %d: %.2Lf%%\n", i, 100.0 * (stats[i][0] + stats[i][1] + stats[i][2]) / (stats[i][0] + stats[i][1] + stats[i][2] + stats[i][3] + stats[i][4] + stats[i][5] + stats[i][6] + stats[i][7] + stats[i][8] + stats[i][9]));
}
return 0;
}
```
注意,这个程序中的使用率是以总时间作为分母,而不是以空闲时间为分母。因此,如果系统中有其它进程在运行,它们的CPU使用率也会计入到这个程序中。如果需要考虑其它进程的CPU使用率,可以使用Linux提供的/proc/[pid]/stat文件来获取进程的CPU使用率。