写一段在Linux下使用C语言计算CPU使用率的代码
时间: 2024-04-29 11:27:09 浏览: 140
获取CPU使用率的C代码
3星 · 编辑精心推荐
当然,我很乐意帮你回答这个问题。以下是在Linux下使用C语言计算CPU使用率的代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
int main() {
long double total_jiffies_start, work_jiffies_start, total_jiffies_end, work_jiffies_end;
char stat[1024];
FILE* fp = NULL;
if ((fp = fopen("/proc/stat", "r")) == NULL) {
fprintf(stderr, "Error: failed to open /proc/stat\n");
exit(EXIT_FAILURE);
}
fgets(stat, 1024, fp);
sscanf(stat, "cpu %Lf %Lf %*Lf %*Lf %*Lf %*Lf %*Lf %*Lf %*Lf %*Lf", &total_jiffies_start, &work_jiffies_start);
fclose(fp);
sleep(1);
if ((fp = fopen("/proc/stat", "r")) == NULL) {
fprintf(stderr, "Error: failed to open /proc/stat\n");
exit(EXIT_FAILURE);
}
fgets(stat, 1024, fp);
sscanf(stat, "cpu %Lf %Lf %*Lf %*Lf %*Lf %*Lf %*Lf %*Lf %*Lf %*Lf", &total_jiffies_end, &work_jiffies_end);
fclose(fp);
long double total_jiffies = total_jiffies_end - total_jiffies_start;
long double work_jiffies = work_jiffies_end - work_jiffies_start;
double cpu_usage = work_jiffies / total_jiffies * 100;
printf("CPU Usage: %.2f%%\n", cpu_usage);
return 0;
}
```
这段代码会读取 `/proc/stat` 文件来获取 CPU 执行周期(jiffies)的信息,然后通过睡眠 1 秒来计算出 CPU 使用率,并输出到标准输出中。
阅读全文