I'm working on a project that requires me to measure time and timestamp events in a concurrent/asynchronous system. I didn't want to use System.currentTimeMillis() because it's not returning a linearly increasing number of time stamps. The user or services such as NTP can change the system clock at any time and the time will leap back and forward.
So what about System.nanoTime()? It seems to return a linearly increasing number of time stamps for the next 292 years from the point you turn on the computer. The JavaDoc doesn't mention any potential problems besides that nanosecond precision is maybe not supported by the underlying operating system. It should be sufficient to measure time or to timestamp events.
It turns out nanoTime()'s behavior is actually quite unspecified and it's unclear what the clock's expected properties are. Chances are it's using the Time Stamp Counter (TSC) and modern computers have one of them for each core. It's up to the underlying Operating System or Hardware to keep these TSCs in sync (or not) or provide some other high precision clock etc. etc. From the developers perspective it's completely unclear what nanoTime() is actually returning.
There are a few things that can happen if nanoTime() is based on TSCs and if there are multiple CPUs or COREs at play or if the underlying Operating System is messing with the CPU/CORE frequencies (e.g. switching to a lower clock speed to save energy). This can be best seen if you're trying to measure time by doing two subsequent nanoTime() calls and something happens in between these calls. Let's take a look at the following example.
Read full article from A big flaw in Java's nanoTime() — kapsi.(de|eu)
No comments:
Post a Comment