How to benchmark Swift code execution?

后端 未结 6 1928
花落未央
花落未央 2020-12-02 10:57

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         


        
6条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-02 11:46

    I like Brad Larson's answer for a simple test that you can even run in a Playground. For my own needs I've tweaked it a bit:

    1. I've wrapped the call to the function I want to test in a testing function, which gives me space to play around with different arguments if I want to.
    2. The testing function returns its name, so I don't have to include the 'title' parameter in the averageTimeTo() benchmarking function.
    3. The benchmarking function allows you to optionally specify how many repetitions to perform (with a default of 10). It then reports both the total and average times.
    4. The benchmarking function prints to the console AND returns the averageTime (which you might expect from a function called 'averageTimeTo'), so there's no need for two separate functions that have almost identical functionality.

    For example:

    func myFunction(args: Int...) {
        // Do something
    }
    
    func testMyFunction() -> String {
        // Wrap the call to myFunction here, and optionally test with different arguments
        myFunction(args: 1, 2, 3)
        return #function
    }
    
    // Measure average time to complete test
    func averageTimeTo(_ testFunction: () -> String, repeated reps: UInt = 10) -> Double {
        let functionName = testFunction()
        var totalTime = 0.0
        for _ in 0..

提交回复
热议问题