SuspendingClock how do I use it

I;m trying to write a function that returns elapsed time in milliseconds. from the developer decimation it looks like I should use SuspendingClock. But beyond that I haven't got a clue. Any suggestions?

Answered by DTS Engineer in 904758022

If you subtract two suspending clock instants you get a Duration value:

let c = SuspendingClock()
let start = c.now
… your code here …
let end = c.now
let delta: Duration = end - start

That’s a 128-bit count of attoseconds. Use the components property to get seconds and attoseconds:

let (seconds, attoseconds) = delta.components

You can tidy this up with the measure(_:) method`:

let delta = c.measure {
    … your code here …
}

Share and Enjoy
—
Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

If you subtract two suspending clock instants you get a Duration value:

let c = SuspendingClock()
let start = c.now
… your code here …
let end = c.now
let delta: Duration = end - start

That’s a 128-bit count of attoseconds. Use the components property to get seconds and attoseconds:

let (seconds, attoseconds) = delta.components

You can tidy this up with the measure(_:) method`:

let delta = c.measure {
    … your code here …
}

Share and Enjoy
—
Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

For the milliseconds part of Quinn’s example, you can convert the Duration like this:

func milliseconds(_ duration: Duration) -> Double {
    let parts = duration.components
    return Double(parts.seconds) * 1_000
        + Double(parts.attoseconds) / 1_000_000_000_000_000
}

let clock = SuspendingClock()
let start = clock.now
// Do the work you want to time here.
let elapsed = milliseconds(clock.now - start)
print(elapsed)

This keeps the fractional milliseconds too. SuspendingClock stops counting while the device is asleep. If that time should count toward your elapsed time, use ContinuousClock instead.

https://developer.apple.com/documentation/swift/duration/components