If it's exactly 2:00 and I tell a Java ScheduledExecutorService to execute a task in one minute, is it possible that the task begins execution even a nanosecond before the system clock hits 2:01?
-
If your timing depends on nanoseconds, you need to be writing in assembler on the bare silicon without an OS involved. – Jim Garrison Oct 17 '21 at 19:16
-
A similar question about C#: https://stackoverflow.com/questions/43113406/can-a-timer-be-early – Dan R. Oct 17 '21 at 21:32
1 Answers
First a couple of definitions:
- Precision - the number of decimal places in a value
- Accuracy - the difference between the measured value and its "true" value (for whatever is considered "true")
No clock you find on a PC will have nanosecond accuracy. Then the question is "accuracy relative to what"?
Remember that light travels about 1 foot in a nanosecond (and an electrical signal about half that), so due to relativity 2:00:00.000000000 here isn't the same time somewhere else, or even across the room (or across the motherboard, for that matter).
Can you time with nanosecond accuracy? Probably not without extremely expensive hardware. You're dependent on the OS updating the internal clock with zero delays, which can involve everything from rare leap seconds to internal clock drift adjustments which might make the clock run a bit faster or slower to keep up with an external time signal (see Network Time Protocol).
So in summary, there are no guarantees that a delay of 1 minute is exactly equal to 60.000000000 seconds, although you can probably count on millisecond accuracy (except if the interval spans a leap-second). It will likely be longer than 60 seconds, though a shorter interval is possible.

- 85,615
- 20
- 155
- 190