#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#define true 1
#define false 0
struct proc_stat
{
unsigned int user_mode;
unsigned int nice;
unsigned int system_mode;
unsigned int idle;
unsigned int iowait;
unsigned int irq;
unsigned int softirq;
};
/*
*
*
*
*/
struct proc_stat pre_stat, tmp_stat ;
//byte in 5 second
unsigned int totalbyte;
//handle for statics
struct sigaction timer;
struct timeval sta, stop;
//read proc status
int read_stat(struct proc_stat * stat)
{
char buf[10][20];
unsigned int tmp;
FILE * fd;
fd = fopen("/proc/stat", "r");
if(fd < 0)
{
printf("fopen(\"/proc/stat\", \"r\") error errno(%d)\n", errno);
return -1;
}
fscanf(fd, "%s %d %d %d %d %d %d %d %d", buf[0],
&stat->user_mode, &stat->nice, &stat->system_mode, &stat->idle,
&stat->iowait, &stat->irq, &stat->softirq, &tmp);
fclose(fd);
return 0;
}
//caculate cpu status
unsigned int cpu_rate(struct proc_stat * start, struct proc_stat * end)
{
unsigned int total;
unsigned int idle_rate;
total = (end->user_mode - start->user_mode) + (end->nice - start->nice) +
(end->system_mode - start->system_mode) + (end->idle - start->idle) +
(end->iowait - start->iowait) + (end->irq - start->irq) +
(end->softirq - start->softirq);
//if care remove /*
/* printf("total:%d %d, %d \n", total, end->idle, start->idle); */
idle_rate = (end->idle - start->idle) * 100 / total;
/* printf("idle:%d\n", idle_rate); */
return (100 - idle_rate);
}
void print_info(int arg)
{
unsigned int msec = 0;
unsigned int rate;
alarm(5);
gettimeofday(&stop , NULL);
msec = (stop.tv_sec * 1000 + stop.tv_usec / 1000) -
(sta.tv_sec * 1000 + sta.tv_usec / 1000);
read_stat(&tmp_stat);
rate = cpu_rate(&pre_stat, &tmp_stat);
printf("cpu_rate: %d%%,time:%d ms\n", rate, msec);
memcpy(&sta, &stop, sizeof(sta));
memcpy(&pre_stat, &tmp_stat, sizeof(tmp_stat)); // cpu rate
}
int main (int argc, char* argv[])
{
//welcom
printf("CPU RATE. compile time %s \n" ,__TIME__);
/////////////////////////////////////////
memset(&timer, 0, sizeof(timer));
timer.sa_flags = SA_RESTART;
timer.sa_handler = print_info;
sigaction(SIGALRM, &timer, NULL);
gettimeofday(&sta , NULL);
read_stat(&pre_stat);
alarm(5);
while(1)
{
pause();
}
return 0;
}
阅读(771) | 评论(0) | 转发(0) |