NanoTime and currentTimeMillis have different speeds on Mac OS

I am trying to measure the duration of a period with both System.nanoTime() and System.currentTimeMillis() . And the longer the period, the greater the difference is obtained from two dimensions.

Here is a small snippet demonstrating the problem:

 public class TimeTest { public static void main(String[] args) throws Exception { long startNanos = System.nanoTime(); long startMillis = System.currentTimeMillis(); while (true) { long nowNanos = System.nanoTime(); long nowMillis = System.currentTimeMillis(); System.out.println((nowMillis - startMillis) - (nowNanos - startNanos) / 1000000); Thread.sleep(100); } } } 

When working on Mac OS with jdk 1.8.0_74, there is a clear tendency that the values ​​decrease by about 2 ms per minute. That is, at first I see only 0 and 1, but after 10 minutes there are values ​​around -20.

I managed to observe this behavior only on mac using jdk8, I could not play it on linux and on windows with jdk 7 and 8.

So the question is: who is lying? I know that nanoTime() should be chosen to measure duration. But in this case, I'm not sure if this is true.

Can someone clarify this topic?

+5
source share
2 answers

If you use NTP, most likely your current TimeMillis is being fixed, so it will most likely be right. NanoTime () is based on clock frequencies / clock frequency. If this frequency is turned off a little, then you will see a constant drift. This should not be based on the Java version, but rather on the OS and hardware.

0
source

Both lie :)

Time cannot be measured with absolute accuracy. Each timer on your computer will always have a slight drift. Since currentTimeMillis and nanoTime can come from different timers, it is only natural that you observe a drift between them. The drift can even change depending on the working state of your computers (for example, the workload on a machine can change its temperature and, in turn, cause a slight change in the clock generator. These effects are small, but they always exist).

In cases where it seems that no drift occurs, both currentTimeMillis and nanoTime are either controlled by the same hardware timer, or there is corrective confusion when working either in the OS or in a virtual machine.

0
source

All Articles