[concurrency-interest] java.lang.System.nanoTime and QueryPerformanceCounter-"Bug"

David Holmes dholmes@dltech.com.au
Wed, 24 Dec 2003 09:32:58 +1000

Michael Mayr wrote:

> During my investigations I also found
> out that on Windows platforms some chipsets cause leaps
> forward in time (up to a few seconds) when using the
> QueryPerformanceCounter-Call (which is -to my knowledge-
> the only way to measure in nanoseconds on Windows).

You can also use assembler code to read the timestamp counter directly
(RDTSC instruction) and perform a calibration to establish a time base
for the counter. However there are numerous problems trying to use the
TSC and various issues with TSC drift across different CPU's in a
system. This is non-trivial stuff for sure. I suspect
QueryPerformanceCounter tries to mask these issues to make it easier
to use.

> I took a look at your viewcvs-webinterface but couldn't
> find any native code. So I couldn't check if you do take
> this fact into account. IMHO leaps should be detected and
> if they are detected nanoTime() should return a nonvalid
> time (e.g. a negative time). I think it is not useful
> having a wrong time with a leap for profiling or anything like this.

There is no notion of an "invalid time" as negative values from
nanoTime are possible. The only use for the return value from nanoTime
is to compare it with another return value from nanoTime.

The implementation is responsible for using the most sensible timing
mechanism to provide nanoTime and to account for as many
idiosyncracies as possible.

David Holmes