Microsecond Timestamp in Java

1,670 views
Skip to first unread message

Robert Deverill

unread,
Nov 27, 2013, 11:20:46 AM11/27/13
to mechanica...@googlegroups.com
Hi

I have a requirement to get a microsecond resolution wall clock timestamp in Java.  We can assume that the OS system clock (linux in this case) is kept up to date (to the microsecond) by hardware clock synchronization.

Has anyone else done this? A simple implementation we have been playing with is using System.currentMillis and System.nanoTime, calculating the offset and then resetting every n seconds.





Peter Lawrey

unread,
Nov 27, 2013, 11:24:30 AM11/27/13
to mechanica...@googlegroups.com

You want the system time via JNI or JNA. This can have micro second resolution.

What I do is use nanoTime for short intervals with a currentTimeMillis at the start of an event for context. Ie i dont try to solve this problem in real time. 

Note: currentTimeMillis is not monotonically increasing and can go backwards.

--
You received this message because you are subscribed to the Google Groups "mechanical-sympathy" group.
To unsubscribe from this group and stop receiving emails from it, send an email to mechanical-symp...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.

Wojciech Kudla

unread,
Nov 27, 2013, 11:52:59 AM11/27/13
to mechanica...@googlegroups.com

We're using gettimeofday over JNR. It's much faster than JNA; 250 ns per call on average.

Jin Mingjian

unread,
Nov 28, 2013, 12:00:03 AM11/28/13
to mechanica...@googlegroups.com
I just right do some investigations in the clock topic recently. 

For Hotspot, System.currentMillis uses gettimeofday, and System.nanoTime uses clock_gettime. They all call to your said "OS system clock". So, I personally think, it is not good reason to use 3rd JNI or JNA or JNR, if no special requirement. JNR is also on the top of JNI tech, and may be a slightly little faster when calliing to library. But it will not exhibit any difference in microsecond resolution level.

The gettimeofday is designed to change with wall clock as Peter has mentioned. And you may expect this from your words.  Generally, the gettimeofday can not have higher resolution than clock_gettime at least for modern common kernel/cpu, IMHO. The advantage of gettimeofday is that it can sync to external atmoic clock source, like via NTP. But this sync brings the standard time but not microsecond resolution to you. 

Jin


Reply all
Reply to author
Forward
0 new messages