title: Measuring execution time - gettimeofday versus clock() versus chrono
body: <p>I have a subroutine that should be executed once every milisecond. I wanted to check that indeed that's what's happening. But I get different execution times from different functions. I've been trying to understand the differences between these functions (there are several SO questions about the subject) but I cannot get my head around the results I got. Please forget the global variables etc. This is a legacy code, written in C, ported to C++, which I'm trying to improve, so is messy.</p>
  
  <pre><code>&lt; header stuff&gt;
  std::chrono::high_resolution_clock::time_point tchrono;
  int64_t tgettime;
  float tclock;
  
  void myfunction(){
  
  &lt;all kinds of calculations&gt;
  
    using ms = std::chrono::duration&lt;double, std::milli&gt;;
    std::chrono::high_resolution_clock::time_point tmpchrono = std::chrono::high_resolution_clock::now();
    printf("chrono %f (ms): \n",std::chrono::duration_cast&lt;ms&gt;(tmpchrono-tchrono).count());
    tchrono = tmpchrono;
  
    struct timeval tv;
    gettimeofday (&amp;tv, NULL);
    int64_t tmpgettime = (int64_t) tv.tv_sec * 1000000 + tv.tv_usec;
    printf("gettimeofday: %lld\n",tmpgettime-tgettime);
    tgettime = tmpgettime;
  
    float tmpclock = 1000.0f*((float)clock())/CLOCKS_PER_SEC;
    printf("clock %f (ms)\n",tmpclock-tclock);
    tclock = tmpclock;
  
    &lt;more stuff&gt;
  }
  </code></pre>
  
  <p>and the output is:</p>
  
  <pre><code>chrono 0.998352 (ms): 
  gettimeofday: 999
  clock 0.544922 (ms)
  </code></pre>
  
  <p>Why the difference? I'd expect clock to be at least as large as the others, or not?</p>