C语言获取CPU使用率(Linux 64位)

#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;
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值