Chinaunix首页 | 论坛 | 博客
  • 博客访问: 618765
  • 博文数量: 172
  • 博客积分: 10010
  • 博客等级: 上将
  • 技术积分: 1252
  • 用 户 组: 普通用户
  • 注册时间: 2009-06-29 22:26
文章分类

全部博文(172)

文章存档

2011年(6)

2010年(7)

2009年(159)

我的朋友

分类: LINUX

2009-07-25 13:12:45

#include
#include
#include
#define  CPU_FILE_PROC_STAT "/proc/stat"
/*the utilization of CPU */
struct cpu_usage_struct
{
 unsigned long cpu_user;
 unsigned long cpu_sys;
 unsigned long cpu_nice;
 unsigned long cpu_idle;
};
double get_cpu_use_rate(const struct cpu_usage_struct *cur,
    const struct cpu_usage_struct *old)
{
 double user,sys,nice,idle,total;
 double cpu_rate;
 user = (double)(cur->cpu_user - old->cpu_user);
 sys = (double)(cur->cpu_sys - old->cpu_sys);
 nice = (double)(cur->cpu_nice - old->cpu_nice);
 idle = (double)(cur->cpu_idle - old->cpu_idle);
 total = user + sys + nice + idle;
 cpu_rate = (1-idle/total)*100;
 return cpu_rate;
}
double get_cpu_free_rate(const struct cpu_usage_struct *cur,
    const struct cpu_usage_struct *old)
{
 double user,sys,nice,idle,total;
 double free_rate;
 user = (double)(cur->cpu_user - old->cpu_user);
 sys = (double)(cur->cpu_sys - old->cpu_sys);
 nice = (double)(cur->cpu_nice - old->cpu_nice);
 idle = (double)(cur->cpu_idle - old->cpu_idle);
 total = user + sys + nice + idle;
 free_rate = (idle /total)*100;
 return free_rate;
}
int get_cpuinfo_from_proc_stat(struct cpu_usage_struct *usage)
{
 FILE *fp = NULL;
 char tmp[10];
 fp = fopen(CPU_FILE_PROC_STAT,"r");
 if(fp == NULL)
 {
  perror("fopen");
  return -1;
 }
 printf("%s,%d\n",__FILE__,__LINE__);
 fscanf(fp,"%s %lu %lu %lu %lu",tmp,&(usage->cpu_user),&(usage->cpu_sys),
     &(usage->cpu_nice),&(usage->cpu_idle));
 printf("%s %d\n",__FILE__,__LINE__);
 fclose(fp);
 printf("%s %d\n",__FILE__,__LINE__);
 return 1;
}
int main()
{
 struct cpu_usage_struct *cur,*old;
 double use_rate,free_rate;
 old = (struct cpu_usage_struct*)malloc(sizeof(struct cpu_usage_struct));
 if(old == NULL)
 {
  perror("malloc error");
  return -1;
 }
 cur = (struct cpu_usage_struct*)malloc(sizeof(struct cpu_usage_struct));
 if(cur == NULL)
 {
  perror("malloc error");
  return -1;
 }
 get_cpuinfo_from_proc_stat(old);
 sleep(100);
 get_cpuinfo_from_proc_stat(cur);
 use_rate = get_cpu_use_rate(cur,old);
 free_rate = get_cpu_free_rate(cur,old);
 printf("use_rate:%lf,free_rate:%lf\n",use_rate,free_rate);
 return 1;
}
阅读(2207) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~