title: How can I get the most accurate time for a process in in C?
body: <p>I am not looking for nanoseconds or accuracy to the umpteenth decimal, however I would like to have some decent accuracy and to minimise margin of error with the results.</p>
  <p>For this, I used sys/time.h, time.h, on a Mac Book Pro and a stop watch (my iPhone's stopwatch app, that is), and I am getting rather inconstant results.</p>
  <p>My iPhone's stopwatch report: 140.66 seconds and the two functions with three trials are seen below:</p>
  <pre class="lang-none prettyprint-override"><code>1. time.h gave me 136.957065 seconds —— sys/time.h gave me 140.335872 seconds
  2. time.h gave me 140.822794 seconds —— sys/time.h gave me 151.858111 seconds
  3. time.h gave me 146.064458 seconds —— sys/time.h gave me 162.149713 seconds
  </code></pre>
  <p>And here is my code snippet:</p>
  <pre class="lang-c prettyprint-override"><code>void myExpensiveFunction()
  {
     struct timeval tv1, tv2;
     gettimeofday(&amp;tv1, NULL);
     clock_t fbegin = clock();
          
     /* expensive algorithm */
          
     clock_t fend = clock();
     gettimeofday(&amp;tv2, NULL);
  
     printf(&quot;Expensive function took: %f seconds\n&quot;, (double)(fend - fbegin) / CLOCKS_PER_SEC);
     printf(&quot;Expensive function took: %f seconds\n&quot;,
       (double)(tv2.tv_usec - tv1.tv_usec) / 1000000 +
       (double)(tv2.tv_sec - tv1.tv_sec));
  }
  </code></pre>
  <p>While this isn't mission critical and I am sure there are some inconsistencies due to my computer itself, I am curious if there is a better function or methodology I should be using or be aware of.  For testing and curiosity sake, I tried this same thing on my Linux mail server, and got similar results, <code>sys/time.h</code> was ten seconds slower.</p>