2

I am trying to compute time lapsed in java using nanoTime. But everytime it gives me different results. Why it is not consistent always ?

Sample code :

long startTime=System.nanoTime();
String.valueOf(number).length();
long endTime = System.nanoTime();
System.out.println(endTime-startTime);
jmj
  • 237,923
  • 42
  • 401
  • 438
coder87
  • 101
  • 12
  • 3
    Mandatory comment; http://stackoverflow.com/questions/504103/how-do-i-write-a-correct-micro-benchmark-in-java – almightyGOSU Jun 03 '15 at 06:32
  • 1
    Why do you need this to be consistent? – defectus Jun 03 '15 at 06:33
  • 2
    Well, because the CPU load and *state* is not always the same (varies each time). As @Gosu suggests, this is not the right way of doing a proper micro benchmarking – TheLostMind Jun 03 '15 at 06:35
  • 1
    Such a code can never give a consistent time; as @defectus says, you have to ask yourself why you need this to be consistent. This looks like a XY problem, so what is it that you want to achieve? – fge Jun 03 '15 at 06:36
  • For consistency, compute time lapsed using milliseconds rather than nanoseconds. – Rajesh Jun 03 '15 at 06:49
  • Well, i am in a situation where i need to compute this time elapsed to nano precision. @defectus yes, i don't need it to be consistent. I asked it here to get more hands-on exp to this qst.I will go through the link to understand it better – coder87 Jun 03 '15 at 07:03

2 Answers2

6

nanoTime() and its sister currentTimeMillis() are not exact and depending on the architecture you run your code on they suffer from rounding (see the javadoc for details):

This method provides nanosecond precision, but not necessarily nanosecond resolution 
(that is, how frequently the value changes) -
no guarantees are made except that the resolution is at least as good
as that of currentTimeMillis().

If you measure the time in order to decide if alternative a or b is faster you are basically doing a micro benchmark. There are frameworks for this and you should use them. Probably the one most known for Java is JMH. If you need to do the same for larger code parts you might consider profiling.

You might want to have a look at this stackoverflow post: How do I write a correct micro-benchmark in Java?

Community
  • 1
  • 1
Marged
  • 10,577
  • 10
  • 57
  • 99
2

The lapsed time will vary depending upon how JVM will execute and allocate the processing time to the thread in which this code executes. I tried multiple runs and always got result in between 9000 to 11000 nanoseconds range. This looks fairly consistent.

AmolB
  • 149
  • 6