linux c语言 统计CPU专用率

    最近在调试中发现应用程序的CPU占用率高,于是想看是那个线程专用了cpu。

    # top

    查看cpu专用率,这个时候打印的是进程级别cpu专用率。再按H,就有打印线程级别的cpu专用信息了

    #top -H

linux 代码实时监控cpu专用率

s_32 Timer_GetCpuStat_FUN(u_64 *user, u_64 *system, u_64 *nice,u_64 *idle, u_64 *iowait, u_64 *irq, u_64 *softirq)
{
    static FILE* fp = NULL;
    s_8 buf[512] = {0}, cpuName[32]={0};

    fp = fopen( "/proc/stat", "r" );
    if(fp == NULL)
    {           
        errorPrintf(PRT_COMM,"查询系统cpu专用率信息异常...\n");
        return -1;
    }
    memset(buf, 0, sizeof(buf));

    fgets( (s_8 *)buf, sizeof(buf), fp );
    sscanf( buf, "%s %lld %lld %lld %lld %lld %lld %lld",\
        cpuName, user, system, nice, idle, iowait, irq, softirq); 

    fclose(fp);
    return 0;
}

/*
FUNCTION:
    统计CPU 专用率函数
    
INPUT:
    secNum : 统计时间间隔,top指令是5s 统计一次推荐使用5s
    maxRate: 设置最高cpu 占用比,当大于等于该数值异常提示
OUTPUT:
    无
RETURN:
    < 0 失败
    > 0 cpu专用率
OTHER:
    接口在定时器函数中周期调用,工程接口1s  掉一次
AUTHER:ybq
*/

s_32 Timer_CpuRate_API(u_16 secNum, u_16 maxRate)
{
    static u_32 num = 0;
    static u_64 oldUser = 0, oldSystem = 0, oldNice = 0,oldIdle = 0, oldIowait = 0, oldIrq = 0, oldSoftirq = 0;
    u_64 cUser = 0, cSystem = 0, cNice = 0,cIdle = 0, cIowait = 0, cIrq = 0, cSoftirq = 0;
    s_32 ret = -1, rate = -1;
    u_64 cTotal = 0, oldTotal = 0;

    if(0 == num%secNum)
    {
        ret = Timer_GetCpuStat_FUN(&cUser, &cSystem, &cNice , &cIdle, &cIowait, &cIrq, &cSoftirq);
        if(ret < 0)
        {
            num++;
            return -1;
        }
        
        if(0 == num)
        {
            oldUser = cUser;
            oldSystem = cSystem;
            oldNice = cIdle;
            oldIdle = cIdle;
            oldIowait = cIowait;
            oldIrq = cIrq;
            oldSoftirq = cSoftirq;
        }else
        {
            oldTotal = oldUser + oldSystem + oldNice + oldIdle + oldIowait + oldIrq + oldSoftirq;
            cTotal = cUser + cSystem + cNice + cIdle + cIowait+ cIrq + cSoftirq;
            //rate = (cSystem - oldSystem)*100/(cTotal - oldTotal);
            rate = (cIdle- oldIdle )*100/(cTotal - oldTotal);
            if(100-rate >= maxRate)
            {
                errorPrintf(PRT_COMM,"CPU专用率(%d)资源大于等于预设(%d),请注意分析...\n", 100-rate, maxRate);
            }
            oldUser = cUser;
            oldSystem = cSystem;
            oldNice = cNice;
            oldIdle = cIdle;
            oldIowait = cIowait;
            oldIrq = cIrq;
            oldSoftirq = cSoftirq;
        }
    }
    num++;
    return rate;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章