+ -
当前位置:首页 → 问答吧 → 通过C程序获得CPU使用情况

通过C程序获得CPU使用情况

时间:2010-08-31

来源:互联网

  1.   #include   <stdio.h>   
  2.   #include   <stdlib.h>   
  3.   #include   <string.h>   
  4.   #include   <errno.h>   
  5.    
  6.   struct   cpu_usage   
  7.   {   
  8.                   unsigned   long   user;   
  9.                   unsigned   long   sys;   
  10.                   unsigned   long   nice;   
  11.                   unsigned   long   idle;   
  12.    
  13.   };   
  14.    
  15.   static   struct   cpu_usage   old_cd,   new_cd;   
  16.   static   tmp[64];   
  17.   void   get_cpu_data(struct   cpu_usage   *pcd)   
  18.   {   
  19.                   FILE   *file   =   NULL;   
  20.                   file   =   fopen("/proc/stat",   "r");   
  21.                   if   (file   ==   NULL)   
  22.                   {   
  23.                                   perror("fopen");   
  24.                                   exit(-1);   
  25.                   }   
  26.                   memset(pcd,   0,   sizeof(struct   cpu_usage));   
  27.                   fscanf(file,   "%s   %lu   %lu   %lu   %lu",   tmp,   &(pcd->user),   &(pcd->sys),   &(pcd->nice),   &(pcd->idle   
  28.   ));   
  29.                   fclose(file);   
  30.   }   
  31.    
  32.   void   cpu_usage()   
  33.   {   
  34.                   double   user,   sys,   nice,   idle,   total;   
  35.    
  36.                   get_cpu_data(&new_cd);   
  37.                   user   =     (double)(new_cd.user   -   old_cd.user);   
  38.                   sys   =     (double)(new_cd.sys   -   old_cd.sys);   
  39.                   nice   =     (double)(new_cd.nice   -   old_cd.nice);   
  40.                   idle   =     (double)(new_cd.idle   -   old_cd.idle);   
  41.                   total   =   user   +   sys   +   nice   +   idle;   
  42.                   memcpy(&old_cd,   &new_cd,   sizeof(struct   cpu_usage));   
  43.                   fprintf(stdout,   "CPU   usage:   %2.1f\%\n",   (idle   /   total)   *   100);   
  44.   }   
  45.    
  46.    
  47.   int   main()   
  48.   {   
  49.                   get_cpu_data(&old_cd);   
  50.                   while(1)   
  51.                   {   
  52.                                   sleep(1);   
  53.                                   cpu_usage();   
  54.                   }   
  55.                   return   0;   
  56.   }   
  57.    
复制代码
其实也可以使用glibtop库实现   
  头文件在/usr/include/glibtop.h

作者: osdba   发布时间: 2010-08-31

这个有命令吧?

作者: ecjtubaowp   发布时间: 2010-08-31