title: timing function call cost
body: <p>I'm trying to see how much time a function call takes using clock_gettime with CLOCK_MONOTONIC. I did this by subtracting the timer overhead from the time of the function call. </p>
  
  <p>I think the time should be consistent but when I loop it, the first time is alway 3x larger than the rest. Also, the time I get outside the loop is different too. Does anyone know what's going on?</p>
  
  <p>(running C on ubuntu 14.04.1)</p>
  
  <hr>
  
  <p><strong>Edit</strong></p>
  
  <p>I was confused as to why the first time in the loop was much larger than the others. I now realize that this probably has something to do with caching.</p>
  
  <p>I think that the first loop caches the timer and function? 
  But when the loop is over, are they uncached? 
  (After the loop, the function call time got bigger)</p>
  
  <p>Output:</p>
  
  <pre><code>Within loop:
  timer   w.func  difference
  198     128     18446744073709551546
  85      78      18446744073709551609
  68      80      12
  64      70      6
  70      68      18446744073709551614
  Outside loop:
  101     115     14
  </code></pre>
  
  <p>My code:</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;stdint.h&gt;
  #include &lt;time.h&gt;
  
  #define NANO 1E9
  #define CLOCK CLOCK_MONOTONIC
  signed long long timediff(struct timespec *tstart_p, struct timespec *tstop_p)
  {
      return ((tstop_p-&gt;tv_sec - tstart_p-&gt;tv_sec)*NANO + tstop_p-&gt;tv_nsec - tstart_p-&gt;tv_nsec);
  }
  
  void function()
  {
  }
  
  int main()
  {
  struct timespec start, stop;
  signed long long timepassed, timeroverhead;
  
  printf("Within loop:\n");
  printf("timer\tfunction\tdifference\n");
  
  int i;
  for (i = 0; i &lt; 5; i++) 
  {
      clock_gettime(CLOCK, &amp;start);
      clock_gettime(CLOCK, &amp;stop);
      timeroverhead = timediff(&amp;start, &amp;stop);
  
      clock_gettime(CLOCK, &amp;start);
      function();
      clock_gettime(CLOCK, &amp;stop);
      timepassed = timediff(&amp;start, &amp;stop);
      printf("%llu\t%llu\t%llu\n", timeroverhead, timepassed, (timepassed-timeroverhead));
  }
  
  clock_gettime(CLOCK, &amp;start);
  clock_gettime(CLOCK, &amp;stop);
  timeroverhead = timediff(&amp;start,&amp;stop);
  
  clock_gettime(CLOCK, &amp;start);
  function();
  clock_gettime(CLOCK, &amp;stop);
  timepassed = timediff(&amp;start, &amp;stop);
  printf("Outside loop:\n");
  printf("%llu\t%llu\t%llu\n", timeroverhead, timepassed, (timepassed - timeroverhead));
  
  
  printf("\n");
  
  return 0;
  }
  </code></pre>