Skip to content

Instantly share code, notes, and snippets.

@jonathanstiansen
Forked from pyrtsa/Profiling.swift
Created November 4, 2015 03:00
Show Gist options
  • Save jonathanstiansen/663771984e7c5a2c1133 to your computer and use it in GitHub Desktop.
Save jonathanstiansen/663771984e7c5a2c1133 to your computer and use it in GitHub Desktop.
Profile a block of code in Swift 2.0
import Foundation
public func profiling<R>(label: String, @noescape _ block: () -> R) -> R {
NSLog("*** %@...", label)
let start = NSDate()
defer {
let end = NSDate()
NSLog("*** %@ took %5.3g seconds", label, end.timeIntervalSinceDate(start))
}
return block()
}
let result: Int? = profiling("heavy computation") {
NSLog("Really computing hard now")
return Int("123")
}
// 2015-06-09 22:32:48.811 repl_swift[39408:2024531] *** heavy computation...
// 2015-06-09 22:32:48.811 repl_swift[39408:2024531] Really computing hard now
// 2015-06-09 22:32:48.812 repl_swift[39408:2024531] *** heavy computation took 0.000195 seconds
@jonathanstiansen
Copy link
Author

Simple but useful way of reasonably profiling. If you want to do it more accurately, you would profile with no block and subtract from the original.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment