Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to benchmark Swift code execution?

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)") 
like image 471
ielyamani Avatar asked Jul 29 '14 00:07

ielyamani


People also ask

How is swift code executed?

You can run the Swift REPL from the command line and enter Swift code directly into it. Whenever you enter valid Swift code in the REPL, it will immediately compile and run it. Lets play around with the Swift REPL a bit. You can access previous lines that you've entered using $R0 etc.

How can I speed up my swift code?

Optimization Level in Build Settings: payment: build size. Use “final” and “private” for methods and classes — payment: constraints with subclass and dispatching. Avoid “print” in release builds — payment: no logs to console. “Inline” Your Code — Payment: duplicate code; code is not “clean”


1 Answers

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.

like image 186
Brad Larson Avatar answered Oct 08 '22 11:10

Brad Larson