I just found System.currentTimeMillis is not accurate on windows XP, now I tried System.nanoTime() with the same code.
Since 1ms = 1,000,000ns, so I think the result should be 15,000,000ns, but it’s not.
See the sample code:
public class NanoTime {
public static void main(String[] args) {
long start = 0;
long end = 0;
while (true) {
if (start == 0) {
start = System.nanoTime();
} else {
long current = System.nanoTime();
if (current != start) {
end = current;
break;
}
}
}
System.out.println("The time interval of your OS: " + (end - start) + "ns");
}
}
The result is:
The time interval of your OS: 655ns
Seems it’s much better than System.currentTimeMillis(). But why? Can we believe this result?
If your Windows XP has SP3 then you can believe that result… on Windows the JVM implements
nanoTime()internally usingQueryPerformanceCounter/QueryPerformanceFrequencyAPI which is basically located in HAL (Hardware abstraction layer) and uses some CPU-internal interval instructions which are rather accurate… it is only good for interval measurements NOT for time handling…For a more elaborate description see http://blogs.oracle.com/dholmes/entry/inside_the_hotspot_vm_clocks and http://juliusdavies.ca/posix_clocks/clock_realtime_linux_faq.html
EDIT – as per comment:
The above mentioned function are used by the JVM itself internally when
nanoTimeis called which has absolutely NOTHING to do with JNI – they are not exposed to Java code!EDIT 2 – as per comments:
nanoTime()is the right tool to measure elapsed time accurately whilecurrentTimeMillisis the right tool to handle absolute time.