Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing System.nanoTime() values resulting from different machines

Is it correct to compare two values resulting from a call to System.nanoTime() on two different machines? I would say no because System.nanoTime() returns a nanosecond-precise time relative to some arbitrary point time by using the Time Stamp Counter (TSC) which is processor dependent.

If I am right, is there a way (in Java) to capture an instant on two different machines and to compare (safely) these values with at least a microsecond precision or even nanotime precision?

System.currentTimeMillis() is not a solution because it is not returning a linearly increasing number of time stamps. The user or services such as NTP can change the system clock at any time and the time will leap back and forward.

like image 814
Laurent Avatar asked Nov 03 '11 19:11

Laurent


People also ask

Is system nanoTime () reliable?

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).

What is System nanoTime ()?

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.

What does nanoTime return?

nanoTime. Returns the current value of the running Java Virtual Machine's high-resolution time source, in nanoseconds. This method can only be used to measure elapsed time and is not related to any other notion of system or wall-clock time.

How accurate is system currentTimeMillis?

currentTimeMillis() actually give the time accurate to the nearest millisecond on Linux, Mac OS and Windows (and since which versions - I know, for example, that Windows only used to be accurate to the nearest 15/16 milliseconds).


1 Answers

You might want to look into the various clock synchronization algorithms available. Apparently the Precision Time Protocol can get you within sub-microsecond accuracy on a LAN.

If you don't need a specific time value but rather would like to know the ordering of various events, you could for instance use Lamport timestamps.

like image 115
Vlad Avatar answered Sep 30 '22 09:09

Vlad