2011-04-01 85 views
14

有关如何使用/ proc/stat中的统计信息获取CPU利用率的许多帖子和参考。然而,他们中的大多数只使用7+ CPU统计中的四个(用户,nice,系统和空闲),忽略了Linux 2.6中存在的剩余jiffie CPU数量(iowait,irq,softirq)。使用/ proc/stat精确计算Linux中的CPU利用率

作为示例,请参阅Determining CPU utilization

我的问题是这样的:iowait/irq/softirq数字是否也计入前四个数字之一(user/nice/system/idle)?换句话说,jiffie总数是否等于前四个数据的总和?或者,jiffie总数是否等于所有7个数据的总和?如果后者是真,则CPU利用率式应采取所有的号码的考虑,这样的:

#include <stdio.h> 
#include <stdlib.h> 

int main(void) 
{ 
    long double a[7],b[7],loadavg; 
    FILE *fp; 

    for(;;) 
    { 
    fp = fopen("/proc/stat","r"); 
    fscanf(fp,"%*s %Lf %Lf %Lf %Lf",&a[0],&a[1],&a[2],&a[3],&a[4],&a[5],&a[6]); 
    fclose(fp); 
    sleep(1); 
    fp = fopen("/proc/stat","r"); 
    fscanf(fp,"%*s %Lf %Lf %Lf %Lf",&b[0],&b[1],&b[2],&b[3],&b[4],&b[5],&b[6]); 
    fclose(fp); 

    loadavg = ((b[0]+b[1]+b[2]+b[4]+b[5]+b[6]) - (a[0]+a[1]+a[2]+a[4]+a[5]+a[6])) 
     /((b[0]+b[1]+b[2]+b[3]+b[4]+b[5]+b[6]) - (a[0]+a[1]+a[2]+a[3]+a[4]+a[5]+a[6])); 
    printf("The current CPU utilization is : %Lf\n",loadavg); 

    } 

    return(0); 
} 
+1

我也很好奇这个问题。你从其他渠道找到答案吗? – justinzane 2012-02-15 01:09:52

+0

另请参阅[此答案](http://stackoverflow.com/a/23376195/85696)。 – danadam 2015-08-06 18:11:10

回答

9

我认为IOWAIT/IRQ /软中断未在第一个4号中的一个计数。你可以看到irqtime_account_process_tick的内核代码中的注释的更多详细信息:

(为Linux kernel 4.1.1

2815 * Tick demultiplexing follows the order 
2816 * - pending hardirq update <-- this is irq 
2817 * - pending softirq update <-- this is softirq 
2818 * - user_time 
2819 * - idle_time   <-- iowait is included in here, discuss below 
2820 * - system time 
2821 * - check for guest_time 
2822 * - else account as system_time 

对于空闲时间处理,参见account_idle_time功能:

2772 /* 
2773 * Account for idle time. 
2774 * @cputime: the cpu time spent in idle wait 
2775 */ 
2776 void account_idle_time(cputime_t cputime) 
2777 { 
2778   u64 *cpustat = kcpustat_this_cpu->cpustat; 
2779   struct rq *rq = this_rq(); 
2780 
2781   if (atomic_read(&rq->nr_iowait) > 0) 
2782     cpustat[CPUTIME_IOWAIT] += (__force u64) cputime; 
2783   else 
2784     cpustat[CPUTIME_IDLE] += (__force u64) cputime; 
2785 } 

如果CPU空闲并且有一些IO挂起,它将计算CPUTIME_IOWAIT中的时间。否则,它计入CPUTIME_IDLE。总结一下,我认为irq/softirq中的jiffies应该算作cpu的“繁忙”,因为它实际上处理了一些IRQ或软IRQ。另一方面,“iowait”中的jiffies应该被认为是cpu的“闲置”,因为它没有做任何事情,而是等待正在发生的IO事件。