title: Accurately Calculating CPU Utilization in Linux using /proc/stat
body: <p>There are a number of posts and references on how to get CPU Utilization using statistics in /proc/stat. However, most of them use only four of the 7+ CPU stats (user, nice, system, and idle), ignoring the remaining jiffie CPU counts present in Linux 2.6 (iowait, irq, softirq).</p>
  
  <p>As an example, see <a href="https://stackoverflow.com/questions/3769405/determining-cpu-utilization">Determining CPU utilization</a>. </p>
  
  <p>My question is this: Are the iowait/irq/softirq numbers also counted in one of the first four numbers (user/nice/system/idle)? In other words, does the total jiffie count equal the sum of the first four stats? Or, is the total jiffie count equal to the sum of all 7 stats? If the latter is true, then a CPU utilization formula should take all of the numbers into account, like this:</p>
  
  <pre class="lang-C prettyprint-override"><code>#include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  
  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",&amp;a[0],&amp;a[1],&amp;a[2],&amp;a[3],&amp;a[4],&amp;a[5],&amp;a[6]);
      fclose(fp);
      sleep(1);
      fp = fopen("/proc/stat","r");
      fscanf(fp,"%*s %Lf %Lf %Lf %Lf",&amp;b[0],&amp;b[1],&amp;b[2],&amp;b[3],&amp;b[4],&amp;b[5],&amp;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);
  }
  </code></pre>