Is `SuspendingClock.measure(_:)` safe to use for benchmarks?

i’ve got some simple benchmarks of the form:

let clock:SuspendingClock = .init()
let duration:Duration = clock.measure 
    for element:Int in insertions
        forest.insert(element, into: &tree)

my question then is, is SuspendingClock.measure(_:) safe to use for this purpose? will things inside the closure get hoisted outside of it?

I’m not an expert but the definition doesn’t allow the work to escape so if it were “getting out” it should give you an error, right?

func measure(_ work: () throws -> Void) rethrows -> Self.Instant.Duration
1 Like

if the compiler inlines the measure(_:) method, it could potentially reorder the work in the passed closure such that some of it executes before the timer starts, or after it stops.

based on the discussion here, it sounded like there was no way to reliably benchmark swift code before the Clock APIs were introduced. i’m interested in whether that has changed in the year since.

Oh, that makes sense. I’d wonder if there was a way to ask the optimizer to not reorder, but that might throw off your benchmarks as well.