Reputation: 89749
We have a few processes in Java that use nanoTime for internal benchmarking (since that is supposed to be accurate within the same thread).
The processes can communicate between themselves.
Is there a standard way of determining the difference in nanoTime between the threads? (e.g., mimic NTP?). Should this be done regularly?
Upvotes: 4
Views: 313
Reputation: 1725
I would not recommend to use it for benchmarking. One reason is that it's performance in somewhat unknown, e.g. on Windows on multiprocessor machine it can be extremely slow.
Regarding to sync and the value itself, on Windows you are guaranteed to have synced value, even on different processors. Also on windows increment rate is constant. Because such properties are supported, retrieving that value is expensive.
On Linux there is no sync between processors, moreover, the increase rate can vary when CPU frequency is changing(e.g. because of power saving).
On Solaris is similar to Linux apart from guarantee that next nanoTime is >= last nanoTime.
Upvotes: 0
Reputation: 403501
The javadoc qualifies the nanoTime() method with a lot of warnings. The gist of it seems to be that you can use it within a block of code to measure elapsed time, giving you "nanosecond precision, but not necessarily nanosecond accuracy".
That's wooly language, probably deliberately so. I would probably avoid comparing two different elapsed time calculations made using nanoTime(), it's likely to give you bad results.
If this is for benchmarking, it may be a better idea to benchmark the same code in a loop, bringing the elapsed time up into the millisecond range, allowing you to use currentTimeMillis() instead, which is more reliable.
Upvotes: 3