-
-
Save boxed/ff6849a1e50e1c8c3bca31383cfd4fb3 to your computer and use it in GitHub Desktop.
Time code execution in Swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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