1

I would like to do some (micro)benchmarking in Swift. I have been using package-benchmark for this. It comes with a blackHole helper function that forces the compiler to assume that a variable is read and thus prevent dead-code elimination.

However, I would like to go a step further and block common subexpression elimination and loop-invariant code motion too. For that I had come up with the following based on the blackHole implementation.

@_optimize(none)
func assumePointeeIsClobbered(_ x: UnsafeMutableRawPointer) {}

My understanding is that this should force the compiler to assume that x can be both read and written to. I tried to use this in the following manner.

@_optimize(none)
func assumePointeeIsClobbered(_ x: UnsafeMutableRawPointer) {}

import Foundation

// NB: I know that this is a very synthetic benchmark that doesn't even measure the latency of sqrt properly, but that is not the point of this question
func sqrtFPI(iter: Int) {
    var x = 3.1415926e104
    let startTime = DispatchTime.now()
    for _ in 1...iter {
        assumePointeeIsClobbered(&x)
        var result = sqrt(x)
        assumePointeeIsClobbered(&result)
    }
    let endTime = DispatchTime.now()
    print(endTime, startTime)
}

But, the sqrt call gets optimized out by the compiler in Swift 6.0.3, but not in 5.10. Compiler Explorer Link.

The diff shows that the benchmarkee (sqrt) gets optimized out in Swift 6.0.3, but not in Swift 5.10. I have the following questions.

  1. Is the behavior in Swift 6.0.3 a bug? If not, then what exactly is the optimizer's view of the function? I.e. why exactly is it allowed to do this transformation?
  2. Is there a better way to implement assumePointeeIsClobbered?
2
  • 2
    IIRC, @_optimize(none) only truly works for symbols in another module. Try extracting assumePointeeIsClobbered to another module and make it public. Commented Mar 7 at 18:36
  • @Alexander Looks like you're right, I'm able to confirm this locally using Swift 6.0.3. Commented Mar 10 at 12:23

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.