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

03 Aug, 2007
Xebia Background Header Wave

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.

FromJan Vermeir
SubjectAccuracy of System.getCurrentTimeMillis()
DateMon 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?

FromJeroen Borgers
SubjectRe: Accuracy of System.getCurrentTimeMillis()
DateMon 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.
FromMachiel Groeneveld
SubjectRe: Accuracy of System.getCurrentTimeMillis()
DateTue 24/07/2007 10:36

Might be of interest: time : Java Glossary
FromJeroen Borgers
SubjectRe: Accuracy of System.getCurrentTimeMillis()
DateTue 24/07/2007 11:06

Some additional info:
Here Java Bug Database
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.
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.

Get in touch with us to learn more about the subject and related solutions

Explore related posts