tags:

views:

1795

answers:

3

On a unix system, is there a way to get a timestamp with microsecond level accuracy in java? Something like C's gettimeofday function.

A: 

This gives the time accurate in milliseconds.

Calendar c = Calendar.getInstance(); // Calendar.getInstance();
c.setTime(date);
c.getTimeInMillis();

This one is more accurate, giving a nano second time.

long bStart = System.nanoTime();

Unfortunately you cannot get the current time at better than millisecond accuracy.

What you can do is grab the current time in milliseconds and then grab the nano time storing both.

You can use the stored nanotime as an anchor point representing 'approximately the date and time right now'.

You can now grab nanotime and that lets you do nanosecond accuracy time to that anchor point, if that is useful.

justinhj
That would be milliseconds, not microseconds.
AlBlue
No, it is _not_ possible to combine the results of these methods to get what Seth asked for.
jarnbjo
And the Calendar way is plain cumbersome. Too much unnecessary overhead. If you need the time in millis, just do `System.currentTimeMillis()`.
BalusC
+5  A: 

No, Java doesn't have that ability.

It does have System.nanoTime(), but that just gives an offset from some previously known time. So whilst you can't take the absolute number from this, you can use it to measure nanosecond (or higher) accuracy.

Note that the JavaDoc says that whilst this provides nanosecond precision, that doesn't mean nanosecond accuracy. So take some suitably large modulus of the return value.

AlBlue
+1 for distinguishing between precision and accuracy.
pavium
One would conjecture that the reasons Java has no getTimeInMicroseconds() include 1) accuracy not available on many platforms, 2) returning millisecond accuracy in a microsecond call leads to application portability issues.
Stephen C
+2  A: 

You can use System.nanoTime():

long start = System.nanoTime();
// do stuff
long end = System.nanoTime();
long microseconds = (end - start) / 1000;

to get time in nanoseconds but it is a strictly relative measure. It has no absolute meaning. It is only useful for comparing to other nano times to measure how long something took to do.

cletus