On Linux, Classpath appears to implement the System.nanoTime() function using the gettimeofday function (see java_lang_VMSystem.c). Since gettimeofday returns a wall-clock time this makes it unreliable for measuring elapsed time, (because the system clock could be changed by another process at any moment.
According to the Sun javadocs:
... This method can only be used to measure elapsed time and is not
related to any other notion of system or wall-clock time. The
value returned represents nanoseconds since some fixed but
arbitrary time ...
In short, gettimeofday is not appropriate for measuring elapsed time. Perhaps the clock_gettime function would work (http://www.tin.org/bin/man.cgi?section=3&topic=clock_gettime) or the getrusage function.
Created attachment 21141 [details]
Patch for System.nanoTime
I use classpath in a productive environment and I depend on a wall-clock-independent implementation of System.nanoTime(). So I created a patch using clock_gettime() instead of gettimeofday().
Looks like a good patch, Roland. Hopefully they will incorporate it into the official code.
The only thing I'd add is some #ifdef logic so that old Linux versions without CLOCK_MONOTONIC support will fallback to the existing gettimeofday implementation.
Module name: classpath
Changes by: Andrew John Hughes <gnu_andrew> 10/11/05 00:09:47
. : ChangeLog
PR44411: Make VMSystem.nanoTime independent of wall time where possible.
2010-11-04 Andrew John Hughes <email@example.com>
Provide a fallback for systems without POSIX timers.
(currentTimeMillis): New function which provides
the behaviour for both Java_java_lang_VMSystem_currentTimeMillis
and the fallback by obtaining the result of gettimeofday.
(Java_java_lang_VMSystem_nanoTime): Return currentTimeMillis
multiplied by a 1000 if a monotonic clock is unavailable.
(Java_java_lang_VMSystem_currentTimeMillis): Split main behaviour
out into currentTimeMillis and then return its result divided by a
2010-07-08 Roland Brand <firstname.lastname@example.org>
Pekka Enberg <email@example.com>
using POSIX monotonic clock support and clock_gettime.
Use old nanoTime method (which uses gettimeofday) to
provide the current time in milliseconds.
(currentTimeMillis()): Make native with its own implementation
rather than using nanoTime, which should be
independent of wall-clock time.
Set target to 0.99