How to benchmark Swift code execution?

后端 未结 6 1926
花落未央
花落未央 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:31

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

    import Foundation
    
    func measure(_ title: String, block: (@escaping () -> ()) -> ()) {
    
        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.

提交回复
热议问题