问题
Does it make sense to synchronize java virtual machines with System.nanoTime () ?
I mean :
- A call System.nanoTime () and puts the results in t1
- A send a packet to B
- when the packet from A is received on B, B call System.nanoTime() and sends the result to A
- when the packet from B is received on A, A call System.nanoTime () and puts the results in t3, puts the time received in the packet from B in t2
- timeshift = (t3 - t1) / 2 - t2
is it correct to use System.nanoTime to do that ?
thanks !
回答1:
is it correct to use System.nanoTime to do that ?
No. System.nanoTime() is only useful for measuring time differences within a single JVM, not absolute time across multiple JVMs.
This method can only be used to measure elapsed time and is not related to any other notion of system or wall-clock time. The value returned represents nanoseconds since some fixed but arbitrary origin time (perhaps in the future, so values may be negative). The same origin is used by all invocations of this method in an instance of a Java virtual machine; other virtual machine instances are likely to use a different origin.
To solve that problem, in general you'd use System.currentTimeMillis()
, but that's still limited by the OS clocks of the two computers. Use NTP to synchronize time across computers.
See Time synchronization between server and Internet using Java.
回答2:
It's not entirely clear what you're trying to achieve.
If you're trying to synchronize clocks, there are specialized protocols for this, such as NTP. nanoTime()
is useless for this in any case since its values are not comparable across JVMs.
If you're trying to measure latency, then repeatedly measure the roundtrip (t3-t1
) and divide by two. For this, nanoTime()
could indeed be used.
回答3:
System.nanoTime() is relative to an arbitary and unspecificied point in time. From what I have observed it appears to be from the uptime of the computer.
This makes comparing the nanoTime on two machines very hard.
timeshift = (t3 + t1) / 2 - t2; // note the + instead of -
The formula you have used can be used to approximative the difference between two machines but it can show enormous variance. One way around this is to perform this 1000 times and take an average or the median, which has given me a stable result in the past.
This figure needs to be updated regularly as even the temprature can speed up or slow down the nano timer.
Note: It is surprising difficult to keep two machines to within a milli-second reliably. ;)
来源:https://stackoverflow.com/questions/7753158/synchronize-java-virtual-machine-with-system-nanotime