改进后的计算CPU的使用率实现

来源:互联网 发布:网络格斗3d游戏 编辑:程序博客网 时间:2024/05/19 01:09

网上查阅了一些资料,看到最多的一个文档,内部是用sleep(1)这样的实现,而sleep这个函数是阻塞睡眠,相当于让cpu在这一秒钟内停运,对整个系统的影响还是非常大的。更严重的是影响通信,甚至错误。

其实修改不是很多,可以使用alarm调用等等。


typedef struct cpu_info{char name[20];      unsigned int user; unsigned int nice;unsigned int system;unsigned int idle; }CPU_USE;void get_cpu_node_info (CPU_USE *cpust);int calculate_cpu_use (CPU_USE *o, CPU_USE *n);int get_cpustat_of_use( void );


/* * @brief: For a time the state of the CPU * @param[out]: struct CPU_USE * @return :  */void get_cpu_node_info (CPU_USE *cpust){    FILE *fd;           int n;               char buff[256];  CPU_USE *cpu_occupy;    cpu_occupy=cpust; fd = fopen ("/proc/stat", "r");    fgets (buff, sizeof(buff), fd);      sscanf (buff, "%s %u %u %u %u", cpu_occupy->name, &cpu_occupy->user, &cpu_occupy->nice,&cpu_occupy->system, &cpu_occupy->idle);      fclose(fd);      }/* * @brief: Occupation calculation rate of CPU * @return : rate of CPU */int calculate_cpu_use (CPU_USE *o, CPU_USE *n){unsigned long od, nd;      unsigned long id, sd, id_t;   int cpu_use = 0;         od = (unsigned long) (o->user + o->nice + o->system +o->idle);nd = (unsigned long) (n->user + n->nice + n->system +n->idle);id_t = n->idle - o->idle;cpu_use = 100 * (nd - od - id_t)/(nd-od);return cpu_use;}  /* * @brief: to obtain the CPU utilization rate * @return : rate */CPU_USE cpu_stat1;   int get_cpustat_of_use( void ){CPU_USE cpu_stat2;    int cpu;      get_cpu_node_info((CPU_USE *)&cpu_stat2);cpu = calculate_cpu_use ((CPU_USE *)&cpu_stat1, (CPU_USE *)&cpu_stat2);   cpu_stat1 = cpu_stat2;return cpu;}



原创粉丝点击