如何对 Swift 代码执行进行基准测试? [英] How to benchmark Swift code execution?

查看:40
本文介绍了如何对 Swift 代码执行进行基准测试?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种方法/软件可以给出执行用 Swift 编写的代码块所需的精确时间,而不是以下内容?

Is there a way/software to give precise time needed to execute a block of code written in Swift, other than the following?

let date_start = NSDate()

// Code to be executed 

println("\(-date_start.timeIntervalSinceNow)")

推荐答案

如果你只想要一个代码块的独立计时函数,我使用以下 Swift 辅助函数:

If you just want a standalone timing function for a block of code, I use the following Swift helper functions:

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)
}

前者将注销给定代码段所需的时间,后者将其作为浮点数返回.作为第一个变体的示例:

The former will log out the time required for a given section of code, with the latter returning that as a float. As an example of the first variant:

printTimeElapsedWhenRunningCode(title:"map()") {
    let resultArray1 = randoms.map { pow(sin(CGFloat($0)), 10.0) }
}

将退出类似:

map() 所用时间:0.0617449879646301 s

Time elapsed for map(): 0.0617449879646301 s

请注意,Swift 基准测试会根据您选择的优化级别而有很大差异,因此这可能只是有用用于 Swift 执行时间的相对比较.即使这可能会在每个 beta 版本的基础上发生变化.

Be aware that Swift benchmarks will vary heavily based on the level of optimization you select, so this may only be useful for relative comparisons of Swift execution time. Even that may change on a per-beta-version basis.

这篇关于如何对 Swift 代码执行进行基准测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆