Swift Tip: Quick Performance Timing
When we want to quickly test the performance of some code, we paste the following function into our project:
@discardableResult
func measure<A>(name: String = "", _ block: () -> A) -> A {
let startTime = CACurrentMediaTime()
let result = block()
let timeElapsed = CACurrentMediaTime() - startTime
print("Time: \(name) - \(timeElapsed)")
return result
}
The above helper measures the execution time of the function we pass in, and prints it out to the console. Because it's generic over the result, we can use it to measure single expressions:
let result = measure { (0..<1_000_000).reduce(0, +) }
Or we can use it to to measure the time of a method call:
measure {
computeLayout()
}
For real performance testing, we like to use Instruments (the new os_signpost API looks like a great addition for exactly these kinds of things) or XCTest's measure, but when all we need is a quick check, the above snippet is really useful.
For your own code, there are many variations you could write: include the line number and name of the calling function, timing asynchronous calls, use more precise logging, and so on.