Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is System.nanoTime() consistent across threads?

I want to count the time elapsed between two events in nanoseconds. To do that, I can use System.nanoTime() as mentioned here. The problem is that the two events are happening in different threads.


Since nanoTime() doesn't return an absolute timestamp but instead can only be used to calculate time differences, I'd like to know if the values I get on the two different threads are consistent with the physical time elapsed between the two events.

like image 851
agentofuser Avatar asked Apr 22 '10 03:04

agentofuser


People also ask

How accurate is system nanoTime?

nanoTime() is a great function, but one thing it's not: accurate to the nanosecond. The accuracy of your measurement varies widely depending on your operation system, on your hardware and on your Java version. As a rule of thumb, you can expect microsecond resolution (and a lot better on some systems).

Is system nanoTime thread safe?

Depending on the system, it can take more than 100 cpu cycles to execute. Not thread safe.

How does system nanoTime work?

nanoTime() method returns the current value of the most precise available system timer, in nanoseconds. The value returned represents nanoseconds since some fixed but arbitrary time (in the future, so values may be negative) and provides nanosecond precision, but not necessarily nanosecond accuracy.

How accurate is system currentTimeMillis?

Regarding accuracy, you are almost correct. On SOME Windows machines, currentTimeMillis() has a resolution of about 10ms (not 50ms).


1 Answers

It's supposed to be, but due to buggy kernels or hardware, the answer can be no, at least in some environments.

like image 75
Steven Schlansker Avatar answered Sep 20 '22 18:09

Steven Schlansker