title: nanoseconds to milliseconds - fast division by 1000000
body: <p>I'm wanting to convert the output from gethrtime to milliseconds.</p>
  
  <p>The obvious way to do this is to divide by 1000000.
  However, I'm doing this quite often and wonder if it could become a bottleneck.</p>
  
  <p>Is there an optimized divide operation when dealing with numbers like 1000000?</p>
  
  <p>Note: Any code must be portable.  I'm using gcc and this is generally on Sparc hardware</p>
  
  <p>Some quick testing using the code below... hope that is right.</p>
  
  <pre><code>#include &lt;sys/time.h&gt;
  #include &lt;iostream&gt;
  
  using namespace std;
  
  const double NANOSECONDS_TO_MILLISECONDS = 1.0 / 1000000.0;
  
  int main()
  {
      hrtime_t start;
      hrtime_t tmp;
      hrtime_t fin;
  
      start = gethrtime();
      tmp = (hrtime_t)(start * NANOSECONDS_TO_MILLISECONDS);
      fin = gethrtime();
  
      cout &lt;&lt; "Method 1"
      cout &lt;&lt; "Original val: " &lt;&lt; start &lt;&lt; endl;
      cout &lt;&lt; "Computed: " &lt;&lt; tmp &lt;&lt; endl;
      cout &lt;&lt; "Time:" &lt;&lt; fin - start &lt;&lt; endl;
  
      start = gethrtime();
      tmp = (start / 1000000);
      fin = gethrtime();
  
      cout "Method 2"    
      cout &lt;&lt; "Original val: " &lt;&lt; start &lt;&lt; endl;
      cout &lt;&lt; "Computed: " &lt;&lt; tmp &lt;&lt; endl;
      cout &lt;&lt; "Time:" &lt;&lt; fin - start &lt;&lt; endl;
  
      return 0;
  }  
  </code></pre>
  
  <p>Example outputs:</p>
  
  <pre><code>Original val: 3048161553965997
  Computed: 3048161553
  Time:82082
  Original val: 3048161556359586
  Computed: 3048161556
  Time:31230
  
  Original val: 3048239663018915
  Computed: 3048239663
  Time:79381
  Original val: 3048239665393873
  Computed: 3048239665
  Time:31321
  
  Original val: 3048249874282285
  Computed: 3048249874
  Time:81812
  Original val: 3048249876664084
  Computed: 3048249876
  Time:34830
  </code></pre>
  
  <p>If this is correct, then the multiple by reciprocal is actually slower in this case.  It's probably due to using floating point math instead of fixed point math.  I will just stick to integer division then which still takes hardly any time at all.</p>