码迷,mamicode.com
首页 > 系统相关 > 详细

Linux CPU使用率获取 c

时间:2020-01-08 14:40:27      阅读:84      评论:0      收藏:0      [点我收藏+]

标签:使用   while   count   ESS   gre   user   oid   long   memset   

Linux CPU使用率获取 C

#include <stdio.h>
#include <unistd.h>
#include <string.h>


typedef struct CPU_PACKED
{
    char name[20];
    unsigned int user;
    unsigned int nice;
    unsigned int system;
    unsigned int idle;
}CPU_OCCUPY;

int cal_cpuoccupy(CPU_OCCUPY *o, CPU_OCCUPY *n)
{
    unsigned long od, nd;
    unsigned long id, sd;
    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 = (unsigned long)(n->user - o->user);
    sd = (unsigned long)(n->system - o->system);

    if(nd-od !=0)
    {
        cpu_use = (int)((sd+id)*100)/(nd-od);

    }
    else
    {
        cpu_use = 0;
    }
    return cpu_use;
}


void get_cpuoccupy(CPU_OCCUPY *cpust)
{
    FILE *fd;
    int n;
    char buf[256];
    CPU_OCCUPY *cpu_occupy;
    cpu_occupy = cpust;
    fd = fopen("/proc/stat", "r");
    fgets(buf, sizeof(buf), fd);
    //memset(cpu_occupy->name,0,sizeof(cpu_occupy->name));
    //cpu_occupy->user=0;
    //cpu_occupy->nice=0;
    //cpu_occupy->system=0;
    //cpu_occupy->idle=0;
    sscanf(buf, "%s %u %u %u %u", cpu_occupy->name, &cpu_occupy->user, &cpu_occupy->nice, &cpu_occupy->system, &cpu_occupy->idle);
    fclose(fd);


}
int display_progress(int progress, int last_char_count)     
{
    int i = 0;

    /*把上次显示的进度条信息全部清空*/
    for (i = 0; i < last_char_count; i++)
    {
        //printf("\b"); 
    }

printf("CPU Usage:[");
    /*此处输出‘=’,也可以是其他字符,仅个人喜好*/
    for (i = 0; i < progress; i++)
    {
            printf("#");  
    }
    //printf(">>");
    /*输出空格截止到第104的位置,仅个人审美*/
    for (i += 2; i < 104; i++) 
    {
            printf(" ");
    }
    /*输出进度条百分比*/
    i = i + printf("%-3d%%]", progress);  
    /*此处不能少,需要刷新输出缓冲区才能显示,
 *     这是系统的输出策略*/
    fflush(stdout);


printf("\r");
    /*返回本次显示进度条时所输出的字符个数*/ 
    return i; 
}

int main()
{
    CPU_OCCUPY cpu_stat1, cpu_stat2;
    int cpu;
    int ret;

    while(1)
    {
        cpu=0;
        get_cpuoccupy((CPU_OCCUPY*)&cpu_stat1);
        //printf("%s,%u,%u,%u,%u\n",cpu_stat1.name,cpu_stat1.user,cpu_stat1.nice,cpu_stat1.system,cpu_stat1.idle);
        sleep(1);
        get_cpuoccupy((CPU_OCCUPY*)&cpu_stat2);
        //printf("%s,%u,%u,%u,%u\n",cpu_stat2.name,cpu_stat2.user,cpu_stat2.nice,cpu_stat2.system,cpu_stat2.idle);
        cpu = cal_cpuoccupy((CPU_OCCUPY *)&cpu_stat1, (CPU_OCCUPY *)&cpu_stat2);
        ret = display_progress(cpu, ret);    
    }
    return 0;
}

Linux CPU使用率获取 c

标签:使用   while   count   ESS   gre   user   oid   long   memset   

原文地址:https://www.cnblogs.com/tianyuanchen/p/12166006.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!