On a unix system, is there a way to get a timestamp with microsecond level accuracy in java? Something like C's gettimeofday function.
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.
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.
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.