Skip to content

Instantly share code, notes, and snippets.

@allevato
Last active Nov 22, 2021
Embed
What would you like to do?
EnumEquals benchmark
import Benchmark
enum OpCode : Equatable {
case number(Double, String = "")
case atomic(String)
case string(String)
case matrix(_ rows: Int, _ cols: Int)
case prompt, plus, minus, times, divide, power, list, equal, notequal, less, leq, greater, geq, elementof,
sin, cos, tan, csc, sec, cot, asin, acos, atan, acsc, asec, acot,
sinh, cosh, tanh, csch, sech, coth, asinh, acosh, atanh, acsch, asech, acoth,
index, function, substitution, factorial, superscriptT, plusorminus, minusorplus, sgn, log, sqrt,
grad, div, curl, lap, optotal, oppartial, sum, product, id, abs, overline, sn, choice, interval,
dot, cross, floor, ceil, ln, exp, arg, real, imag, Re, Im, prime, hat, besselj, conditional, piecewise,
integral, mod, min, max, clamp, Count, Sum, Mean, StdDev, slider, set, Transpose, Trace, Det,
Rotate, Interpolate, And, Or, Not, Inf, Sup, lim, partial, total, dataIndex, atan2, square, powfrac,
piecewiseConditional, labeledPiecewise(Int)
}
/// Prevents the value of `x` from being discarded by the optimizer.
///
/// TODO: when https://github.com/google/swift-benchmark/issues/69 is resolved consider using that
/// facility instead.
@inline(__always)
fileprivate func doNotOptimizeAway<T>(_ x: T) {
@_optimize(none)
func assumePointeeIsRead(_ x: UnsafeRawPointer) {}
withUnsafePointer(to: x) { assumePointeeIsRead($0) }
}
/// Returns `x`, preventing its value from being statically known by the optimizer.
///
/// TODO: when https://github.com/google/swift-benchmark/issues/74 is resolved consider using that
/// facility instead.
@inline(__always)
fileprivate func hideValue<T>(_ x: T) -> T {
@_optimize(none)
func assumePointeeIsWritten<T>(_ x: UnsafeMutablePointer<T>) {}
var copy = x
withUnsafeMutablePointer(to: &copy) { assumePointeeIsWritten($0) }
return copy
}
benchmark("x == .plus", settings: Iterations(10_000_000)) { state in
let x = hideValue(OpCode.string("x"))
var sum = 0
try state.measure {
sum += (x == .plus) ? 0 : 1
}
doNotOptimizeAway(sum)
}
benchmark(".plus == x", settings: Iterations(10_000_000)) { state in
let x = hideValue(OpCode.string("x"))
var sum = 0
try state.measure {
sum += (.plus == x) ? 0 : 1
}
doNotOptimizeAway(sum)
}
Benchmark.main()
// swift-tools-version:5.1
import PackageDescription
let package = Package(
name: "EnumEquals",
products: [
.executable(
name: "EnumEquals",
targets: ["EnumEquals"]),
],
dependencies: [
.package(url: "https://github.com/google/swift-benchmark.git", from: "0.1.0"),
],
targets: [
.target(
name: "EnumEquals",
dependencies: ["Benchmark"]),
]
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment