Clock, Duration and measuring time

suggest change

Before Swift 5.7, time in Swift code was usually a TimeInterval (a Double number of seconds), a Date, a DispatchTime, or a raw count of nanoseconds passed to Task.sleep(nanoseconds:). Each API used its own unit and its own idea of "now".

Swift 5.7 added three types to the standard library that replace most of these:

The standard library has two clocks, ContinuousClock and SuspendingClock.

This article covers:

These types are in the standard library. You don't need import Foundation for them. Only formatted() comes from Foundation. On Apple platforms they need macOS 13, iOS 16 or later.

The examples were compiled and run with Swift 6.4 on Windows, in the Swift 6 language mode:

swiftc -swift-version 6 main.swift -o main.exe

All timings below come from that machine. They show proportions, not numbers you should expect on yours.

Duration

You create a Duration with a static function named after the unit:

let timeout: Duration = .seconds(5)
let frame = Duration.milliseconds(16)
let tiny = Duration.nanoseconds(250)
let precise = Duration.seconds(1.5)        // Double is accepted too

print(timeout, frame, tiny, precise)
print(Duration.zero)

let total = timeout + frame * 3
print(total)                     // 5.048 seconds
print(timeout - .seconds(7))     // negative durations are allowed
print(frame / 4)                 // divide by an integer
print(timeout / frame)           // divide by a Duration: Double
print(frame > .milliseconds(10))
print([Duration.seconds(1), .milliseconds(10), .microseconds(5)].max()!)

Output:

5.0 seconds 0.016 seconds 2.5e-07 seconds 1.5 seconds
0.0 seconds
5.048 seconds
-2.0 seconds
0.004 seconds
312.5
true
1.0 seconds

The factories are .seconds, .milliseconds, .microseconds and .nanoseconds. Each takes an integer or a Double. There is no .minutes or .hours. Write .seconds(5 * 60).

Duration supports +, -, * and / by an integer, and comparison. It is Hashable, Codable and Sendable. Dividing one duration by another gives a Double, the ratio. "How many frames fit in 5 seconds" is timeout / frame.

Because the type carries the unit, a call like Task.sleep(for: .milliseconds(500)) can't be misread. The older Task.sleep(nanoseconds: 500_000_000) was easy to get wrong by a factor of 1000.

Inside a Duration, and converting it to numbers

A Duration is stored as a 128-bit count of attoseconds (10^-18 s). components splits it into whole seconds and the attoseconds left over. Use it, or division, to get a plain number for an API that wants one:

let d = Duration.seconds(2) + .milliseconds(250)
let (seconds, attoseconds) = d.components
print(seconds, attoseconds)

// to a Double number of seconds (for example a TimeInterval)
let asDouble = Double(seconds) + Double(attoseconds) * 1e-18
print(asDouble)
print(d / .seconds(1))

// to whole milliseconds
print(seconds * 1000 + attoseconds / 1_000_000_000_000_000)
print(Int(d / .milliseconds(1)))

// built from the two parts
print(Duration(secondsComponent: 3, attosecondsComponent: 500_000_000_000_000_000))

Output:

2 250000000000000000
2.25
2.25
2250
2250
3.5 seconds

d / .seconds(1) is the shortest way to get a TimeInterval for older Foundation APIs. Int(d / .milliseconds(1)) gives whole milliseconds. The components version is exact even for very large values, where a Double loses precision.

Formatting durations

print(duration) is meant for debugging. For text that people read, Foundation adds formatted(), with two styles. .time(pattern:) looks like a stopwatch. .units() spells out the units:

import Foundation

let d = Duration.seconds(3725) + .milliseconds(480)   // 1h 2m 5.48s

// default: hours:minutes:seconds
print(d.formatted())

// .time(pattern:) for clock-like output
print(d.formatted(.time(pattern: .hourMinute)))
print(d.formatted(.time(pattern: .hourMinuteSecond)))
print(d.formatted(.time(pattern: .minuteSecond)))
print(d.formatted(.time(pattern: .hourMinuteSecond(padHourToLength: 2, fractionalSecondsLength: 2))))

// .units() for "1 hr, 2 min" style output
print(d.formatted(.units()))
print(d.formatted(.units(width: .wide)))
print(d.formatted(.units(allowed: [.minutes, .seconds], width: .narrow)))
print(d.formatted(.units(allowed: [.seconds, .milliseconds], width: .abbreviated)))
print(d.formatted(.units(width: .wide, maximumUnitCount: 2)))

let small = Duration.microseconds(1534)
print(small.formatted(.units(allowed: [.milliseconds, .microseconds])))
print(small.formatted(.units(allowed: [.milliseconds], fractionalPart: .show(length: 2))))
print(d.formatted(.units(width: .wide).locale(Locale(identifier: "de_DE"))))

Output:

1:02:05
1:02
1:02:05
62:05
01:02:05.48
1 hr, 2 min, 5 secs
1 hour, 2 minutes, 5 seconds
62m 5s
3,725 secs, 480 ms
1 hour, 2 minutes
1 ms, 534 μs
1.53 ms
1 Stunde, 2 Minuten und 5 Sekunden

Things to note:

Clocks and instants

clock.now returns an Instant of that clock. Instants can't be printed in a useful way and have no meaning on their own. They are useful for subtracting and comparing:

import Foundation

let clock = ContinuousClock()
let start = clock.now

var sum = 0
for i in 0..<5_000_000 { sum &+= i * i }

let elapsed = clock.now - start          // Instant - Instant = Duration
print("sum:", sum)
print("took:", elapsed)
print("took:", elapsed.formatted(.units(allowed: [.milliseconds], fractionalPart: .show(length: 1))))

// the same with the static shortcut and duration(to:)
let t0 = ContinuousClock.now
Thread.sleep(forTimeInterval: 0.05)
print(t0.duration(to: .now) >= .milliseconds(50))

// instants can be moved and compared
let deadline = start + .seconds(2)       // or start.advanced(by: .seconds(2))
print(deadline > start, deadline - start)
print(clock.now < deadline)

Output (debug build):

sum: 4773166019248396768
took: 0.0730453 seconds
took: 73.0 ms
true
true 2.0 seconds
true

ContinuousClock.now is a static shortcut for ContinuousClock().now. The clocks are empty structs, so creating one costs nothing.

ContinuousClock vs SuspendingClock

Both clocks are monotonic: they never go backwards. They differ in what happens while the computer sleeps:

Choose by the question you are asking:

Question Clock
Has the 30 second network timeout passed? ContinuousClock
Is the cached token older than 10 minutes? ContinuousClock
How long did this function take? either (they agree unless the machine sleeps mid-measurement)
How much running time did an animation or a game get? SuspendingClock

Each clock has its own Instant type, so the compiler stops you from mixing them:

let continuous = ContinuousClock()
let suspending = SuspendingClock()
print(continuous.minimumResolution)
print(suspending.minimumResolution)

let c = continuous.now
let s = suspending.now
print(c)
print(s)
print(c - s)
error: binary operator '-' cannot be applied to operands of type 'ContinuousClock.Instant' and 'SuspendingClock.Instant'

Without the last line, it prints:

1e-07 seconds
1e-07 seconds
Instant(_value: 329843.4011171 seconds)
Instant(_value: 329843.40111740003 seconds)

minimumResolution is the smallest step the clock can tell apart. On Windows it is 100 ns for both clocks. The printed instant values are an implementation detail. Don't parse them or save them, and don't compare them across processes or reboots.

Why not Date?

Date() reads the wall clock. The wall clock can jump: NTP corrects it, the user changes it, the system adjusts it. Then Date().timeIntervalSince(start) can come out much too large, or negative. Use Date for when something happened ("created at 14:05"). Use a Clock for how long something took. The same goes for CFAbsoluteTimeGetCurrent(), which also reads the wall clock.

DispatchTime.now() is monotonic and still fine in code that uses Dispatch. In new code, ContinuousClock does the same job and gives you a Duration instead of a UInt64 count of nanoseconds.

Measuring code with measure

Taking now twice and subtracting is common enough that Clock has a method for it. measure runs a closure and returns how long it took:

let clock = ContinuousClock()

var words: [String] = []
let elapsed = clock.measure {
    for i in 0..<200_000 {
        words.append("word\(i)")
    }
}
print(words.count, "words in", elapsed)

let sortTime = clock.measure {
    words.sort()
}
print("sort:", sortTime)

func loadConfig() async throws -> [String: String] {
    try await Task.sleep(for: .milliseconds(30))
    return ["mode": "fast"]
}

var config: [String: String] = [:]
let loadTime = try await clock.measure {
    config = try await loadConfig()
}
print(config, "loaded in", loadTime)

Output:

200000 words in 0.0178649 seconds
sort: 0.0258393 seconds
["mode": "fast"] loaded in 0.0459329 seconds

measure returns only the Duration. To keep a result, assign it to a variable from inside the closure, as with config above. There is an async overload, and both versions rethrow, so try await clock.measure { ... } works for async throwing code.

The 30 ms sleep took about 46 ms. That's not a bug in measure. A sleep lasts at least as long as you ask, and often longer. The section on sleeping below explains why.

Micro-benchmarks that tell the truth

A single measure call is fine for a rough "is this slow?" check. If you want to compare two implementations, three mistakes produce nonsense numbers.

1. Measuring a debug build. -Onone, the default for swiftc and swift build, can be orders of magnitude slower than -O, and not by the same factor for every kind of code. Benchmark with swiftc -O or swift build -c release.

2. Letting the optimizer delete the work. With -O, the compiler removes code whose result is never used:

let numbers = (0..<100_000).map { ($0 &* 7919) % 100_003 }
let clock = ContinuousClock()

let unused = clock.measure {
    var hits = 0
    for n in 0..<500 where numbers.contains(n) { hits += 1 }
}
print("result unused:", unused)

var total = 0
let used = clock.measure {
    var hits = 0
    for n in 0..<500 where numbers.contains(n) { hits += 1 }
    total = hits
}
print("result used:  ", used, "hits:", total)

Compiled with swiftc -O:

result unused: 1.7e-06 seconds
result used:   0.0071155 seconds hits: 500

The first loop was removed completely. 1.7 µs is the cost of reading the clock twice. Always use the result: return it, store it, and print something derived from it at the end.

3. Trusting one run. The first run pays for page faults, cold caches and lazy initialization. Later runs vary because of other processes and CPU frequency changes. Do a warm-up run, repeat, and report the minimum and the median.

A small helper that does all three:

import Foundation

func benchmark(_ name: String, iterations: Int = 10,
               _ body: () -> Int) {
    let clock = ContinuousClock()
    var checksum = body()                    // warm-up run, not counted
    var times: [Duration] = []
    for _ in 0..<iterations {
        var result = 0
        times.append(clock.measure { result = body() })
        checksum &+= result
    }
    times.sort()
    let median = times[times.count / 2]
    print(name, "min:", times.first!.ms, "median:", median.ms,
          "max:", times.last!.ms, "checksum:", checksum)
}

extension Duration {
    var ms: String {
        formatted(.units(allowed: [.milliseconds], fractionalPart: .show(length: 3)))
    }
}

let numbers = (0..<100_000).map { ($0 &* 7919) % 100_003 }
let lookup = Set(numbers)

benchmark("array") {
    (0..<500).count { numbers.contains($0) }
}
benchmark("set") {
    (0..<500).count { lookup.contains($0) }
}

Compiled with swiftc -O:

array min: 7.320 ms median: 7.703 ms max: 8.756 ms checksum: 5500
set min: 0.017 ms median: 0.017 ms max: 0.017 ms checksum: 5500

The body returns an Int, and benchmark adds every result to a checksum it prints. The optimizer can't prove the work is unneeded, so it can't remove it. The checksum is also a cheap check that both versions compute the same thing. count(where:) needs Swift 6.0. The gap here is O(n) Array.contains against an O(1) Set lookup (see Allocation Performance for another cost to keep in mind).

For serious work, use a benchmarking package such as package-benchmark. It adds statistics, memory counters and comparison against a saved baseline. measure is the building block underneath.

Sleeping: Task.sleep(for:) and tolerance

Task.sleep(for:) suspends the current task without blocking a thread (see async and await). It uses ContinuousClock. How long does it really sleep?

let clock = ContinuousClock()

for requested in [Duration.milliseconds(1), .milliseconds(10), .milliseconds(50)] {
    let actual = try await clock.measure {
        try await Task.sleep(for: requested)
    }
    print("asked for", requested, "slept", actual)
}

// other spellings of the same thing
try await Task.sleep(for: .milliseconds(20), tolerance: .milliseconds(5))
try await Task.sleep(until: .now + .milliseconds(20), clock: .continuous)
try await clock.sleep(for: .milliseconds(20))
try await SuspendingClock().sleep(until: .now + .milliseconds(20))
print("done")

Output:

asked for 0.001 seconds slept 0.0054748 seconds
asked for 0.01 seconds slept 0.0153089 seconds
asked for 0.05 seconds slept 0.0642528 seconds
done

The task wakes up no earlier than requested. How much later depends on the OS timer and on how busy the executor is. On this Windows machine it was 4 to 14 ms late in the run above. In another run, the 1 ms sleep took 15 ms. Don't use sleep for precise timing, and don't assume sleep(for: .milliseconds(1)) sleeps for 1 ms.

tolerance lets the system wake you up later than the deadline, by up to that amount, so it can group timers and save power. Leave it nil (the default) unless you know the timing doesn't matter much.

Every form of sleep checks for cancellation. When the task is cancelled, the sleep ends right away and throws CancellationError. That's why it is usually try await, not try? await. Tasks and cancellation covers this in detail.

Task.sleep(nanoseconds:) still exists. In new code, use Task.sleep(for:).

Deadlines with sleep(until:)

sleep(for:) means "this much time from now". sleep(until:) means "until this instant". The difference matters when you repeat something on a schedule.

A periodic job that does some work and then sleeps for the interval drifts. Each tick takes the interval plus the time of the work plus the oversleep. If you compute each deadline from the previous deadline instead, the errors don't add up:

func doWork() {
    // stands in for a few milliseconds of real work per tick
    var x = 0
    for i in 0..<300_000 { x &+= i }
    precondition(x != 42)
}

let clock = ContinuousClock()
let interval = Duration.milliseconds(50)
let ticks = 20

// 1. sleep(for:) after the work: errors add up
var start = clock.now
for _ in 0..<ticks {
    doWork()
    try await Task.sleep(for: interval)
}
print("sleep(for:)   total:", clock.now - start, "expected:", interval * ticks)

// 2. sleep(until:) a precomputed deadline: errors don't add up
start = clock.now
var next = start
for _ in 0..<ticks {
    doWork()
    next += interval
    try await clock.sleep(until: next)
}
print("sleep(until:) total:", clock.now - start, "expected:", interval * ticks)

Output:

sleep(for:)   total: 1.2529875 seconds expected: 1.0 seconds
sleep(until:) total: 1.0120215 seconds expected: 1.0 seconds

In this run, the first loop fell a quarter of a second behind after 20 ticks. The second loop is only as late as its last wake-up.

An overall deadline for retries

The same idea gives you an overall time budget. Compute the deadline once, then let every retry check against it. "Give up 500 ms after we started" stays true however long each attempt takes:

import Foundation

struct NotReady: Error {}
struct DeadlineExceeded: Error {}

func checkServer(attempt: Int, readyAt: Int) async throws -> String {
    try await Task.sleep(for: .milliseconds(30))       // pretend network call
    if attempt < readyAt { throw NotReady() }
    return "up on attempt \(attempt)"
}

func retry<T>(until deadline: ContinuousClock.Instant,
              delay: Duration = .milliseconds(100),
              _ operation: (Int) async throws -> T) async throws -> T {
    var attempt = 1
    while true {
        do {
            return try await operation(attempt)
        } catch {
            let wakeUp = ContinuousClock.now + delay
            if wakeUp >= deadline { throw DeadlineExceeded() }
            print("  attempt \(attempt) failed: \(error)")
            try await Task.sleep(until: wakeUp)
            attempt += 1
        }
    }
}

let clock = ContinuousClock()
for readyAt in [3, 100] {
    let start = clock.now
    do {
        let status = try await retry(until: start + .milliseconds(500)) { attempt in
            try await checkServer(attempt: attempt, readyAt: readyAt)
        }
        print(status)
    } catch {
        print("gave up:", error)
    }
    print("elapsed:", (clock.now - start).formatted(.units(allowed: [.milliseconds])))
}

Output:

  attempt 1 failed: NotReady()
  attempt 2 failed: NotReady()
up on attempt 3
elapsed: 316 ms
  attempt 1 failed: NotReady()
  attempt 2 failed: NotReady()
  attempt 3 failed: NotReady()
gave up: DeadlineExceeded()
elapsed: 466 ms

The loop gives up as soon as the next attempt would start after the deadline. It doesn't sleep first and find out later. If you need to cancel one slow call when its time runs out, race it against a sleeping child task. Structured concurrency with async let and TaskGroup shows a withTimeout helper built that way.

Taking a Clock as a parameter

Code that sleeps is slow to test. A retry with exponential backoff of 100 + 200 + 400 ms makes every test that hits it wait 0.7 s. The fix is to pass the clock in. Clock has a primary associated type for its duration, so some Clock<Duration> accepts any clock that measures time in Duration:

import Synchronization

struct Flaky: Error {}

// Retries with exponential backoff: 100 ms, 200 ms, 400 ms, ...
func retry<T>(clock: some Clock<Duration>,
              attempts: Int,
              firstDelay: Duration = .milliseconds(100),
              _ operation: (Int) async throws -> T) async throws -> T {
    var delay = firstDelay
    for attempt in 1..<attempts {
        do {
            return try await operation(attempt)
        } catch {
            try await clock.sleep(for: delay)
            delay *= 2
        }
    }
    return try await operation(attempts)    // last try, errors propagate
}

// A clock for tests: sleeping returns at once and moves `now` forward.
final class TestClock: Clock {
    struct Instant: InstantProtocol {
        var offset: Duration = .zero
        func advanced(by duration: Duration) -> Instant {
            Instant(offset: offset + duration)
        }
        func duration(to other: Instant) -> Duration {
            other.offset - offset
        }
        static func < (a: Instant, b: Instant) -> Bool {
            a.offset < b.offset
        }
    }

    private let current = Mutex(Instant())
    var now: Instant { current.withLock { $0 } }
    var minimumResolution: Duration { .zero }

    func sleep(until deadline: Instant, tolerance: Duration?) async throws {
        try Task.checkCancellation()
        current.withLock { now in
            if now < deadline { now = deadline }
        }
    }
}

func flakyJob(attempt: Int) throws -> Int {
    if attempt < 4 { throw Flaky() }
    return attempt
}

var start = ContinuousClock.now
var result = try await retry(clock: ContinuousClock(), attempts: 4, flakyJob)
print("ContinuousClock: attempt", result, "real time:", ContinuousClock.now - start)

let testClock = TestClock()
start = ContinuousClock.now
result = try await retry(clock: testClock, attempts: 4, flakyJob)
print("TestClock:       attempt", result, "real time:", ContinuousClock.now - start)
print("time on the test clock:", testClock.now.offset)

Output:

ContinuousClock: attempt 4 real time: 0.714035 seconds
TestClock:       attempt 4 real time: 3.19e-05 seconds
time on the test clock: 0.7 seconds

To write a clock you need:

Clock requires Sendable, because a clock may be used from many tasks at once. TestClock keeps its mutable now in a Mutex from the Synchronization module (Swift 6.0). That makes a final class with only let properties Sendable without any @unchecked.

This TestClock jumps straight to each deadline. That's enough for sequential code like retry. A test can now check the backoff exactly (testClock.now.offset == .milliseconds(700)) and finish in microseconds. See Swift Testing: @Test and #expect for writing that as a test. To test code where several tasks sleep at once, use a "manual" clock: it keeps the sleepers waiting until the test calls advance(by:). The open-source swift-clocks package provides both kinds.

Summary

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents