http://hi.baidu.com/lionpanther/item/e908c37abdaf1c3f71442380
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
struct occupy
{
char name[20];
unsigned int user;
unsigned int nice;
unsigned int system;
unsigned int idle;
};
float g_cpu_used;
int cpu_num;
void cal_occupy(struct occupy *, struct occupy *);
void get_occupy(struct occupy *);
int main()
{
struct occupy ocpu[10];
struct occupy ncpu[10];
int i;
cpu_num = sysconf(_SC_NPROCESSORS_ONLN);
for(;;)
{
sleep(1);
get_occupy(ocpu);
sleep(1);
get_occupy(ncpu);
for (i=0; i<cpu_num; i++)
{
cal_occupy(&ocpu[i], &ncpu[i]);
printf("%f \n", g_cpu_used);
}
}
}
void cal_occupy (struct occupy *o, struct occupy *n)
{
double od, nd;
double id, sd;
double scale;
od = (double) (o->user + o->nice + o->system +o->idle);//第一次(用户+优先级+系统+空闲)的时间
nd = (double) (n->user + n->nice + n->system +n->idle);//第二次(用户+优先级+系统+空闲)的时间
scale = 100.0 / (float)(nd-od);
id = (double) (n->user - o->user);
sd = (double) (n->system - o->system);
g_cpu_used = ((sd+id)*100.0)/(nd-od);
}
void get_occupy (struct occupy *o)
{
FILE *fd;
int n;
char buff[1024];
fd = fopen ("/proc/stat", "r");
fgets (buff, sizeof(buff), fd);
for(n=0;n<cpu_num;n++)
{
fgets (buff, sizeof(buff),fd);
sscanf (buff, "%s %u %u %u %u", &o[n].name, &o[n].user, &o[n].nice,&o[n].system, &o[n].idle);
fprintf (stderr, "%s %u %u %u %u\n", o[n].name, o[n].user, o[n].nice,o[n].system, o[n].idle);
}
fclose(fd);
}