title: Why is the CPU time different with every execution of this program?
body: <p>I have a hard time understanding processor time. The result of this program:</p>
  
  <pre><code>#include &lt;iostream&gt;
  #include &lt;chrono&gt;
  
  // the function f() does some time-consuming work
  void f()
  {
      volatile long double d;
      int size = 10000;
      for(int n=0; n&lt;size; ++n)
         for(int m=0; m&lt;size; ++m)
             d = n*m;
  }
  
  int main()
  {
      std::clock_t start = std::clock();
      f();
      std::clock_t end = std::clock();
  
      std::cout &lt;&lt; "CPU time used: "
                &lt;&lt; (end - start)
                &lt;&lt; "\n";
  }
  </code></pre>
  
  <p>Seems to randomly fluctuate between 210 000, 220 000 and 230 000. At first I was amazed, why these discrete values. Then I found out that <code>std::clock()</code> returns only <a href="http://en.cppreference.com/w/cpp/chrono/c/clock" rel="nofollow">approximate processor time</a>. So probably the value returned by <code>std::clock()</code> is rounded to a multiple of 10 000. This would also explain why the maximum difference between the CPU times is 20 000 (10 000 == rounding error by the first call to <code>std::clock()</code> and 10 000 by the second).</p>
  
  <p>But if I change to <code>int size = 40000;</code> in the body of <code>f()</code>, I get fluctuations in the ranges of 3 400 000 to 3 500 000 which cannot be explained by rounding.</p>
  
  <p>From what I read about the <a href="http://en.wikipedia.org/wiki/Central_processing_unit" rel="nofollow">clock rate</a>, on Wikipedia:</p>
  
  <blockquote>
    <p>The CPU requires a fixed number of clock ticks (or clock cycles) to
    execute each instruction. The faster the clock, the more instructions
    the CPU can execute per second.</p>
  </blockquote>
  
  <p>That is, if the program is deterministic (which I hope mine is), the CPU time needed to finish should be:</p>
  
  <ol>
  <li>Always the same </li>
  <li>Slightly higher than the number of instructions carried out</li>
  </ol>
  
  <p>My experiments show neither, since my program needs to carry out at least <code>3 * size * size</code> instructions. Could you please explain what I am doing wrong?</p>