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.
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).
Depending on the system, it can take more than 100 cpu cycles to execute. Not thread safe.
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.
Regarding accuracy, you are almost correct. On SOME Windows machines, currentTimeMillis() has a resolution of about 10ms (not 50ms).
It's supposed to be, but due to buggy kernels or hardware, the answer can be no, at least in some environments.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With