Skip to content

Instantly share code, notes, and snippets.

@boxed
Forked from aschmied/timeIt.swift
Last active May 4, 2016 13:37
Show Gist options
  • Save boxed/ff6849a1e50e1c8c3bca31383cfd4fb3 to your computer and use it in GitHub Desktop.
Save boxed/ff6849a1e50e1c8c3bca31383cfd4fb3 to your computer and use it in GitHub Desktop.
Time code execution in Swift
import CoreFoundation
func timeIt(m: () -> ()) -> (Double, Int) {
let startTime = CFAbsoluteTimeGetCurrent()
var numberOfRuns = 0
while true {
m()
numberOfRuns += 1
let elapsed = CFAbsoluteTimeGetCurrent() - startTime
if elapsed > 0.5 { // we run the function up to 0.5 seconds, assuming here that we want to sample functions that are pretty fast
return (Double(numberOfRuns) / elapsed, numberOfRuns)
}
}
}
let N = 800
var B = [Float](count: N, repeatedValue: 0)
let (opsPerSecond, samples) = timeIt({
for i in 0..<N {
B[i] = Float(i)
}
})
print("\(opsPerSecond) ops/second, \(samples) samples")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment