title: cpu utilization in C
body: <p>I was trying to get %CPU utilization with C. I have seen this solution : <a href="https://stackoverflow.com/questions/8501706/how-to-get-the-cpu-usage-in-c">How to get the CPU Usage in C?</a></p>
  
  <p>Hence I had tried with the helps provided there : </p>
  
  <pre><code>#include &lt;time.h&gt;
  #include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  #include &lt;sys/times.h&gt;
  #include &lt;unistd.h&gt;
  #define NANO2SEC 1000000000
  
  struct timespec gettimenow;
  double getWtime;
  double getCtick;
  int ncore;
  double cpu_util;
  
  double get_wall_time () {
      if (clock_gettime(CLOCK_REALTIME,&amp;gettimenow)){
          //error handle
          return 0;
      }
      return ( (double)gettimenow.tv_sec + ( (double)gettimenow.tv_nsec / NANO2SEC ) );
  }
  
  
  double get_cpu_time () {
      return ( (double)clock() / sysconf (_SC_CLK_TCK));
  }
  
  int core_logical () {
      return (sysconf(_SC_NPROCESSORS_ONLN));
  }
  
  void main() {
      getWtime = get_wall_time ();
      printf("\nWall time : %f \n", getWtime);
  
      getCtick = get_cpu_time ();
      printf("\nCPU time : %f \n", getCtick);
  
      ncore = core_logical ();
      printf("\nNo of cores : %d \n", ncore);
  
      cpu_util = (getCtick/ncore/getWtime);
      printf("\nCPU Utilization : %f %% \n", cpu_util);
  }
  </code></pre>
  
  <p>The o/p :</p>
  
  <p>Wall time : 1439132892.054816 </p>
  
  <p>CPU time : 17.280000 </p>
  
  <p>No of cores : 2 </p>
  
  <p>CPU Utilization : 0.000000 % </p>
  
  <p>But with top command I found that cpu utilization is not at all 0% it is more that that. ie. 6.2 %
  I want to know % of CPU utilized at current time.</p>