swift-benchmark
swift-benchmark copied to clipboard
Add a blackHole
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).
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) }
}