#include <stdio.h>
#include <string.h>
#include <unistd.h>
typedef struct cpu_info
{
char name[8];
unsigned long user;
unsigned long nice;
unsigned long system;
unsigned long idle;
unsigned long iowait;
unsigned long irq;
unsigned long softirq;
} CPUInfo;
inline unsigned long GetCPUTotalTime(CPUInfo* pstCPUInfo)
{
return pstCPUInfo->user + pstCPUInfo->nice + pstCPUInfo->system +
pstCPUInfo->idle + pstCPUInfo->iowait + pstCPUInfo->irq + pstCPUInfo->softirq;
}
void DisplayCPUInfo(CPUInfo* pstCPUInfo)
{
printf("%s %lu %lu %lu %lu %lu %lu %lu\n", pstCPUInfo->name, pstCPUInfo->user, pstCPUInfo->nice, pstCPUInfo->system,
pstCPUInfo->idle, pstCPUInfo->iowait, pstCPUInfo->irq, pstCPUInfo->softirq);
}
int GetCPUInfo(CPUInfo *pstCPUInfo)
{
FILE * fp = fopen("/proc/stat", "r");
char buf[1024];
fgets(buf, sizeof(buf), fp);
sscanf(buf,"%s %lu %lu %lu %lu %lu %lu %lu",
pstCPUInfo->name, &pstCPUInfo->user, &pstCPUInfo->nice,&pstCPUInfo->system,
&pstCPUInfo->idle, &pstCPUInfo->iowait, &pstCPUInfo->irq,&pstCPUInfo->softirq);
fclose(fp);
return 0;
}
unsigned long GetCPUUsageRate()
{
CPUInfo stCPUInfo1;
CPUInfo stCPUInfo2;
memset(&stCPUInfo1, 0, sizeof(stCPUInfo1));
memset(&stCPUInfo2, 0, sizeof(stCPUInfo2));
GetCPUInfo(&stCPUInfo1);
DisplayCPUInfo(&stCPUInfo1);
sleep(1);
GetCPUInfo(&stCPUInfo2);
DisplayCPUInfo(&stCPUInfo2);
unsigned long nTotalTime = GetCPUTotalTime(&stCPUInfo2) - GetCPUTotalTime(&stCPUInfo1);
unsigned long nIdleTime = stCPUInfo2.idle - stCPUInfo1.idle;
printf("total time: %lu\n", nTotalTime);
printf("idle time: %lu\n", nIdleTime);
if (nTotalTime == 0)
{
return 0;
}
unsigned long usage = (nTotalTime - nIdleTime) * 100 / nTotalTime;
return usage;
}
int main()
{
for (; ; )
{
printf("CPU usage: %lu%%\n", GetCPUUsageRate());
sleep(3);
}
return 0;
}
Linux系统下获取CPU的使用率
最新推荐文章于 2024-06-13 12:53:47 发布