Measuring Code Execution Speed

Measuring code exec speed comes up once in a while, generally if you’re coding an algorithm or doing some sort of heavy processing. To be able to see how long it took for your code to execute you just have to do the follwing:

let startTime = CFAbsoluteTimeGetCurrent()
//Run your code here
let dt = CFAbsoluteTimeGetCurrent() - startTime
print("\(dt) seconds")

Another way to do this is to write a general purpose function that takes a code block like this:

func measureExecTime<T>(_ block: () -> T) -> T {
    let startTime = CACurrentMediaTime()
    let result = block()
    let dt = CACurrentMediaTime() - startTime
    print("Exec Time: \(dt) seconds")
    return result
}

func test() -> Int {
    for i in 0..<10000 {
        let _ = 1 * i
    }
    return 0
}

print(measureCodeExec {
    test()
})