Best of Xebia tech list July 2007: Accuracy of System.getCurrentTimeMillis()

Erwin van der Koogh

At Xebia we have an internal mailing list where a lot of interesting technical discussions take place. Because we have a passion for knowledge sharing, we thought we'd give you a glimpse of some recent topics. This is the first of a series we plan to do.

We choose this particular mail thread because it answers a technical question a lot of people might have. And it also introduces a little known feature of Java 5.

From Jan Vermeir
Subject Accuracy of System.getCurrentTimeMillis()
Date Mon 23/07/2007 15:51

Hi, we're measuring elapsed time for processing a message. each measured operation takes a couple of milliseconds, so I was wondering what the accuracy of System.getCurrentTimeMillis() is. I have some vague recollection about accuracy not actually being milliseconds, as the name would suggest, and that it may vary with platform and JVM vendor.

Does anyone know for sure?

Jan.

From Jeroen Borgers
Subject Re: Accuracy of System.getCurrentTimeMillis()
Date Mon 23/07/2007 15:54

The timing granularity is dependent on the operating system, many operating systems measure time in units of tens of milliseconds. I am not aware of different VM's acting differently here.

Since Java 5 there is the API call System.nanoTime() which can give you more accuracy, it returns the current value of the most precise available system timer, in nanoseconds. It provides nanosecond precision, but not necessarily nanosecond accuracy, again dependent on the OS. This one is only for relative comparisons, within the same VM.

What for do you use this? With benchmarking, you usually want to time long enough periods only, like seconds, so you don't have to bother about this accuracy.

Regards,
Jeroen.

From Machiel Groeneveld
Subject Re: Accuracy of System.getCurrentTimeMillis()
Date Tue 24/07/2007 10:36

Might be of interest: http://mindprod.com/jgloss/time.html

From Jeroen Borgers
Subject Re: Accuracy of System.getCurrentTimeMillis()
Date Tue 24/07/2007 11:06

Some additional info:

Here http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6440250 it states that on Windows XP, getNanoTime is more accurate than currentTimeMillis, but it is more costly to execute. So, don't use it too much.

And on
http://forum.java.sun.com/thread.jspa?threadID=5119176&messageID=9413087
some more info on Linux:

On Linux things seem to be more distinct. In order to perform
System.nanoTime() as specified, the VM needs a monotonic clock and processes clock_gettime. If CLOCK_MONOTONIC is not supported then there is no monotonic clock available for the VM and System.nanoTime() behaves as gettimeofday. Gettimeofday measures with microseconds accuracy.

Regards,
Jeroen.

Comments (0)

    Add a Comment