title: Measure CPU time on Windows using GetProcessTimes
body: <p>I would like to measure <a href="http://en.wikipedia.org/wiki/Central_processing_unit" rel="nofollow">CPU</a> time of some function. I know how to use <code>GetProcessTimes</code>, but I have a problem implementing it with some kind of 'restarting':</p>
  
  <p>Normally, I would do it like this:</p>
  
  <pre><code>#include "stdafx.h"
  #include &lt;math.h&gt;
  #include &lt;windows.h&gt;
  
  double cputimer()
  {
      FILETIME createTime;
      FILETIME exitTime;
      FILETIME kernelTime;
      FILETIME userTime;
  
      if ( GetProcessTimes( GetCurrentProcess( ),
          &amp;createTime, &amp;exitTime, &amp;kernelTime, &amp;userTime ) != -1 )
      {
          SYSTEMTIME userSystemTime;
          if ( FileTimeToSystemTime( &amp;userTime, &amp;userSystemTime ) != -1 )
              return (double)userSystemTime.wHour * 3600.0 +
              (double)userSystemTime.wMinute * 60.0 +
              (double)userSystemTime.wSecond +
              (double)userSystemTime.wMilliseconds / 1000.0;
      }
  }
  
  int _tmain(int argc, _TCHAR* argv[])
  {
      double start, stop;
      long sum = 0L;
  
      start = cputimer();
      for (long long i = 1; i &lt; 10000000; i++){
          sum += log((double)i);
      }
      stop = cputimer();
  
      printf("Time taken: %f [seconds]\n", stop - start);
  
      return 0;
  }
  </code></pre>
  
  <p>But with 'reset' I'm not sure if I have right results:</p>
  
  <pre><code>#include "stdafx.h"
  #include &lt;math.h&gt;
  #include &lt;windows.h&gt;
  
  #define START    1
  #define STOP    0
  
  double cputimer(int reset)
  {
      FILETIME createTime;
      FILETIME exitTime;
      FILETIME kernelTime;
      FILETIME userTime;
  
      double now = 0, then = 0;
  
      if ( GetProcessTimes( GetCurrentProcess( ),
          &amp;createTime, &amp;exitTime, &amp;kernelTime, &amp;userTime ) != -1 )
      {
          SYSTEMTIME userSystemTime;
          if ( FileTimeToSystemTime( &amp;userTime, &amp;userSystemTime ) != -1 )
              now = (double)userSystemTime.wHour * 3600.0 +
              (double)userSystemTime.wMinute * 60.0 +
              (double)userSystemTime.wSecond +
              (double)userSystemTime.wMilliseconds / 1000.0;
      }
  
      if(reset)
      {
          then = now;
      }
      else
      {
          then = now - then;
      }
  
      return then;
  }
  
  int _tmain(int argc, _TCHAR* argv[])
  {
      double s;
      long sum = 0L;
  
      cputimer(START);
      for (long long i = 1; i &lt; 10000000; i++){
          sum += log((double)i);
      }
      s = cputimer(STOP);
  
  
      printf("Time taken: %f [seconds]\n", s);
  
      return 0;
  }
  </code></pre>
  
  <p>Am I doing it correctly?</p>