Beware of System.nanoTime() in Java

The documentation for System.nanoTime() (and the function’s name itself) leads developers to believe it’s a much more accurate timer than anything else Java provides. Depending on which set of documentation you read, it claims to use “the most precise available system timer”. While I can’t speak for any architecture other than x86, I can state that System.nanoTime() is broken for multi-CPU or multi-core x86 systems, and generally unreliable on all x86 systems. The problem lies in the RDTSC instruction which retrieves the number of CPU ticks since the CPU started. On multi-core systems, each core will have its own tick count, and they will not match, so every time your process switches CPUs, you get a different measurement. The issue is compounded by the fact that some power management systems actually alter the CPU’s frequency to save power, which breaks the functionality even on single core, single CPU systems.

In general, do not use System.nanoTime() in any program which you don’t plan to strongly control how it is run, and the environment it is run in.

Leave a Reply