Comparing instants from two instances of `ContinuousClock`?

is it safe to compare instants between two separately-initialized ContinuousClocks?

let c1:ContinuousClock = .init()
let c2:ContinuousClock = .init()

let t1:ContinuousClock.Instant =  c1.now
let t2:ContinuousClock.Instant =  c2.now
2 Likes

Good question. Based on my study, yes it is, and the question can be answered in two ways:

By review of the design, you can see that one can obtain a ContinuousClock.Instant via the static property now without instantiating any clock, and this instant can be advanced and compared to other instants or passed to ContinuousClock.sleep(until:). It would not be logical to vend such a static API if ContinuousClock.Instants were like string indices and each valid only with reference to a specific instance of ContinuousClock.

By inspection of the implementation, you can see that ContinuousClock has no stored properties whatsoever, and any two instances of that clock are interchangeable because they have no state of their own. The instance property now is implemented by returning the static property now.

The only limitations on comparison of two ContinuousClock.Instants really appear to be exactly as documented: the instants must both be obtained locally (i.e., not distributed from another machine) and during the same execution of a program (not, for example, decoded from a previous run).

5 Likes

thanks, that’s good to know!

is this true of other clock types, like SuspendingClock, which has a similar static now property?

To reinforce the previous (more detailed answer); yes it is definitely safe for those clocks.

1 Like

is this a guarantee of Clock types in general, or just those two standard library clock implementations?

Generally for any clock; no. Clocks may have their own state. For example if you had a clock that is manually ratcheted that would not have the same now.

My guess is that any non-testing-based clock would likely work similarly to SuspendingClock and ContinuousClock but there is no general expectation that should apply uniformly.

1 Like