Linux CPU使用率获取 c

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;
}

相关推荐