inconsistent time elapsed in java

帅比萌擦擦* 提交于 2021-02-10 06:32:13

问题


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);

回答1:


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?




回答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.



来源:https://stackoverflow.com/questions/30612464/inconsistent-time-elapsed-in-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!