title: C find elapsed time in C Linux
body: <p>I have to calculate the time taken by a function to complete.
  This function is called in a loop and I want to find out the total time.
  Usually the time is very less in either nano or micro seconds.</p>
  
  <p>To find out the elapsed time I used functions gettimeofday() using struct timeval and clock_gettime() using struct  timespec.</p>
  
  <p>Problem is time return by timeval in seconds is correct but in micro seconds wrong.
  Similarly the time returned by timespec in nano seconds is wrong.
  Wrong in the sense they do not tally with the time returned in seconds.</p>
  
  <p>For clock_gettime() I tried both CLOCK_PROCESS_CPUTIME_ID and CLOCK_MONOTONIC.
  Using clock() also does not help.</p>
  
  <p>Code snippet:</p>
  
  <pre><code>struct timeval funcTimestart_timeval, funcTimeEnd_timeval;
  struct timespec funcTimeStart_timespec, funcTimeEnd_timespec;
  
  unsigned long elapsed_nanos = 0;
  unsigned long elapsed_seconds = 0;
  unsigned long diffInNanos = 0;
  
  unsigned long Func_elapsed_nanos = 0;
  unsigned long Func_elapsed_seconds = 0;
  
  while(...)
  {
     gettimeofday(&amp;funcTimestart_timeval, NULL);
     clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &amp;funcTimeStart_timespec);
     ...
     demo_func();
     ...
     gettimeofday(&amp;funcTimeEnd_timeval, NULL);
     clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &amp;funcTimeEnd_timespec);
  
     elapsed_seconds = funcTimeEnd_timeval.tv_sec - funcTimestart_timeval.tv_sec;
     Func_elapsed_seconds+= elapsed_seconds;
  
     elapsed_nanos = funcTimeEnd_timespec.tv_nsec - funcTimeStart_timespec.tv_nsec;
     Func_elapsed_nanos+ = elapsed_nanos;
  }
  
  printf("Total time taken by demo_func() is %lu seconds( %lu nanoseconds )\n", Func_elapsed_seconds, Func_elapsed_nanos );
  </code></pre>
  
  <p>Printf output:</p>
  
  <pre><code>Total time taken by demo_func() is 60 seconds( 76806787 nanoseconds )
  </code></pre>
  
  <p>See that the time in seconds and nanoseconds do not match.</p>
  
  <p>How to resolve this issue or any other appropriate method to find elapsed time?</p>