Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save theoknock/9dbcb6dfe52c6c4c0b2270ce9a36f8db to your computer and use it in GitHub Desktop.
Save theoknock/9dbcb6dfe52c6c4c0b2270ce9a36f8db to your computer and use it in GitHub Desktop.
Testing non-branching alternatives to ternary expressions (array-based vectorized expression vs. inline bitwise operation v. ternary conditional expressions). The vectorized expression narrowly beat the ternary; the bitwise operation lags twice over.
import CoreFoundation
import Foundation
var a = 3
var b = 7
var c = 5
var d = 10
func measureTime(for expression: () -> Void, iterations: Int) -> Double {
var totalTime: CFAbsoluteTime = 0
for _ in 0 ..< iterations {
let start = CFAbsoluteTimeGetCurrent()
expression()
let end = CFAbsoluteTimeGetCurrent()
totalTime += (end - start)
}
return totalTime / Double(iterations)
}
// Measure time for the array-based vectorized expression
let arrayAverageTime = measureTime(
for: {
let aVec = [a, a]
let bVec = [b, b]
let cVec = [c, c]
let dVec = [d, d]
let diff = zip(aVec, bVec).map { $0 - $1 }
let wordBit = Int.bitWidth
let sign = diff.map { $0 >> (wordBit - 1) }
let xorCD = zip(cVec, dVec).map { $0 ^ $1 }
let resultVec = zip(sign, xorCD).map { ($0 & $1) ^ d }
_ = resultVec[0]
}, iterations: 1_000_000
)
print("Average time for the array-based vectorized expression: \(arrayAverageTime) seconds")
// Measure time for the inline bitwise expression
let bitwiseAverageTime = measureTime(
for: {
let wordBit = Int.bitWidth
let diff = a - b
let sign = diff >> (wordBit - 1)
let xorCD = c ^ d
let result = (sign & xorCD) ^ d
_ = result
}, iterations: 1_000_000
)
print("Average time for the inline bitwise expression: \(bitwiseAverageTime) seconds")
// Measure time for the conditional expression
let conditionalAverageTime = measureTime(
for: {
_ = (a < b) ? c : d
}, iterations: 1_000_000
)
print("Average time for the conditional expression: \(conditionalAverageTime) seconds")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment