inconsistent time elapsed in java -


i trying compute time lapsed in java using nanotime. everytime gives me different results. why not consistent ?

sample code :

long starttime=system.nanotime(); string.valueof(number).length(); long endtime = system.nanotime(); system.out.println(endtime-starttime); 

nanotime() , sister currenttimemillis() not exact , depending on architecture run code on suffer rounding (see javadoc details):

this method provides nanosecond precision, not nanosecond resolution  (that is, how value changes) - no guarantees made except resolution @ least of currenttimemillis(). 

if measure time in order decide if alternative or b faster doing micro benchmark. there frameworks , should use them. 1 known java jmh. if need same larger code parts might consider profiling.

you might want have @ stackoverflow post: how write correct micro-benchmark in java?


Comments