说明:在linux环境下实现2秒一次的监控cpu使用率。
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
// cpu info
struct occupy {
char name[20];
unsigned int user;
unsigned int nice;
unsigned int system;
unsigned int idle;
};
float g_cpu_used;
int cpu_num;
// read cpu info from /proc/stat这里读取文件得到一些数值,这些数值可用来计算cpu使用率
void get_occupy(struct occupy *p)
{
FILE *fp;
int i;
char buff[1024];
if ((fp = fopen("/proc/stat", "r")) == NULL) {
fprintf(stderr, "cant open /proc/stat\n");
fclose(fp);
}
fgets(buff, sizeof(buff), fp);
for (i=0; i<cpu_num; i++) {
fgets(buff, sizeof(buff), fp);
sscanf(buff, "%s%u%u%u%u", p[i].name, &(p[i].user), &(p[i].nice), &(p[i].system), &(p[i].idle));
}
fclose(fp);
}
// calculate cpu occupation计算cpu使用率
void cal_occupy(struct occupy *p1, struct occupy *p2)
{
double od, nd;
od = (double)(p1->user + p1->nice + p1->system + p1->idle);
nd = (double)(p2->user + p2->nice + p2->system + p2->idle);
g_cpu_used = ((p2->user + p2->system + p2->nice) - (p1->user + p1->system + p1->nice)) / (nd - od) * 100;
}
int main(int argc, char