swift-benchmark icon indicating copy to clipboard operation
swift-benchmark copied to clipboard

Add a blackHole

Open dabrahams opened this issue 5 years ago • 1 comments

The library should provide a way to ensure that code under test isn't optimized away. The only reliable way I know of to do this that doesn't cost more than a function call is:

notOptimizedAway<T>(_ x: T) { 
  withUnsafePointer(to: x) { opaqueCFunctionTakingVoidConstStar($0) }
}

(storing values into Any can be costly if they need to be boxed, and anyway if the compiler can prove the Any is never read, it may one day optimize it out).

dabrahams avatar Aug 27 '20 21:08 dabrahams

Maybe this is better, though it uses a compiler internal:

/// Prevents the value of `x` from being discarded by the optimizer.
///
/// See https://github.com/google/swift-benchmark/issues/69
@inline(__always)
fileprivate func doNotOptimizeAway<T>(_ x: T) {
  
  @_optimize(none) 
  func assumePointeeIsRead(_ x: UnsafeRawPointer) {}
  
  withUnsafePointer(to: x) { assumePointeeIsRead($0) }
}

dabrahams avatar Aug 27 '20 23:08 dabrahams