title: Is System.nanoTime() completely useless?
body: <p>As documented in the blog post <em><a href="http://www.principiaprogramatica.com/2008/04/25/beware-of-systemnanotime-in-java/" rel="noreferrer">Beware of System.nanoTime() in Java</a></em>, on x86 systems, Java's System.nanoTime() returns the time value using a <a href="http://en.wikipedia.org/wiki/Central_processing_unit" rel="noreferrer">CPU</a> specific counter. Now consider the following case I use to measure time of a call:</p>
  
  <pre><code>long time1= System.nanoTime();
  foo();
  long time2 = System.nanoTime();
  long timeSpent = time2-time1;
  </code></pre>
  
  <p>Now in a multi-core system, it could be that after measuring time1, the thread is scheduled to a different processor whose counter is less than that of the previous CPU. Thus we could get a value in time2 which is <em>less</em> than time1. Thus we would get a negative value in timeSpent.</p>
  
  <p>Considering this case, isn't it that System.nanotime is pretty much useless for now?</p>
  
  <p>I know that changing the system time doesn't affect nanotime. That is not the problem I describe above. The problem is that each CPU will keep a different counter since it was turned on. This counter can be lower on the second CPU compared to the first CPU. Since the thread can be scheduled by the OS to the second CPU after getting time1, the value of timeSpent may be incorrect and even negative.</p>