#include <string.h>
#include <stdio.h>
int main()
{
FILE *fp;
char buf[128];
char cpu[5];
long int user, nice, sys, idle, iowait, irq, softirq;
long int all1, all2, idle1, idle2;
float usage; //CPU Occupancy rate
fp = fopen("/proc/stat", "r");
if (fp == NULL)
{
printf("fopen:");
return 0;
}
fgets(buf, sizeof(buf), fp); //first get cpu rate
sscanf(buf, "%s%ld%ld%ld%ld%ld%ld%ld", cpu, &user, &nice, &sys, &idle, &iowait, &irq, &softirq);
all1 = user + nice + sys + idle + iowait + irq + softirq; //all ues time
idle1 = idle; //all idle time
rewind(fp); //Reset file stream
sleep(1);
memset(buf, 0, sizeof(buf));
cpu[0] = '\0';
user = nice = sys = idle = iowait = irq = softirq = 0;
fgets(buf, sizeof(buf), fp); //second get cpu rate
sscanf(buf, "%s%ld%ld%ld%ld%ld%ld%ld", cpu, &user, &nice, &sys, &idle, &iowait, &irq, &softirq);
all2 = user + nice + sys + idle + iowait + irq + softirq;
idle2 = idle;
usage = (float)(all2 - all1 - (idle2 - idle1)) / (all2 - all1) * 100;
if(usage > 90)
{
usage = 90.0;
}
fclose(fp);
printf("usage = %.2f%%\n",usage);
return 0;
}
C语言获取CPU使用率(Linux 64位)
最新推荐文章于 2024-10-11 00:40:20 发布