有没有一种方法/软件可以提供执行一段用 Swift 编写的代码所需的精确时间,除了以下内容?
let date_start = NSDate()
// Code to be executed
println("\(-date_start.timeIntervalSinceNow)")
最佳答案
如果您只需要一个代码块的独立计时函数,我可以使用以下 Swift 辅助函数:
func printTimeElapsedWhenRunningCode(title:String, operation:()->()) {
let startTime = CFAbsoluteTimeGetCurrent()
operation()
let timeElapsed = CFAbsoluteTimeGetCurrent() - startTime
print("Time elapsed for \(title): \(timeElapsed) s.")
}
func timeElapsedInSecondsWhenRunningCode(operation: ()->()) -> Double {
let startTime = CFAbsoluteTimeGetCurrent()
operation()
let timeElapsed = CFAbsoluteTimeGetCurrent() - startTime
return Double(timeElapsed)
}
前者将记录给定代码段所需的时间,后者将其作为 float 返回。作为第一个变体的示例:
printTimeElapsedWhenRunningCode(title:"map()") {
let resultArray1 = randoms.map { pow(sin(CGFloat($0)), 10.0) }
}
将注销类似:
Time elapsed for map(): 0.0617449879646301 s
请注意 Swift benchmarks will vary heavily based on the level of optimization you select ,所以这可能只对 Swift 执行时间的相对比较有用。甚至这可能会在每个测试版的基础上发生变化。
关于swift - 如何对 Swift 代码执行进行基准测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25006235/