How to benchmark Swift code execution?

有没有一种方法/软件可以提供执行用Swift编写的代码块所需的精确时间,以下情况除外?

let date_start = NSDate()

// Code to be executed 

println("(-date_start.timeIntervalSinceNow)")

If you want to get insight into performance of a certain block of code and make sure performance doesn't hurt when you make edits, best thing would be using XCTest's measuring performance functions, like measure(_ block: () -> Void) .

Write a unit test that executes method you want to benchmark, and that unit test will run it multiple times giving you time needed and deviation of results

func testExample() {

    self.measure {
        //do something you want to measure
    }
}

You can find more info in apple docs under Testing with Xcode -> Performance Testing


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

will log out something like:

Time elapsed for map(): 0.0617449879646301 s

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.


You can use this function to measure asynchronous as well as synchronous code:

import Foundation

func measure(_ title: String, block: (() -> ()) -> ()) {

    let startTime = CFAbsoluteTimeGetCurrent()

    block {
        let timeElapsed = CFAbsoluteTimeGetCurrent() - startTime
        print("(title):: Time: (timeElapsed)")
    }
}

So basically you pass a block that accepts a function as a parameter, which you use to tell measure when to finish.

For example to measure how long some call called "myAsyncCall" takes, you would call it like this:

measure("some title") { finish in
    myAsyncCall {
        finish()
    }
    // ...
}

For synchronous code:

measure("some title") { finish in
     // code to benchmark
     finish()
     // ...
}

This should be similar to measureBlock from XCTest, though I don't know how exactly it's implemented there.

链接地址: http://www.djcxy.com/p/31670.html

上一篇: Swift在处理数字方面真的很慢吗?

下一篇: 如何基准Swift代码执行?