Skip to content

Instantly share code, notes, and snippets.

@dennislysenko
Created February 24, 2016 18:13
Show Gist options
  • Save dennislysenko/b0e4afe852367d1ff7d8 to your computer and use it in GitHub Desktop.
Save dennislysenko/b0e4afe852367d1ff7d8 to your computer and use it in GitHub Desktop.
Profile your Swift code when you're too lazy to use Instruments
// Profile your code when you're too lazy to use Instruments
// Method one: get the time to execute a block
func getTimeToExecute(block: () throws -> Void) rethrows -> NSTimeInterval {
let start = NSDate().timeIntervalSince1970
try block()
return NSDate().timeIntervalSince1970 - start
}
// example:
let time = getTimeToExecute {
someLongRunningFunction()
}
print("Execution took \(time) seconds")
// Method two: profile a named block inline (shorthand)
func profile(name: String, block: () throws -> Void) rethrows {
let time = try getTimeToExecute(block)
print("Profiling: \(name) took \(Int(time * 1000)) ms")
}
// example:
profile("longRunningFunction") {
longRunningFunction()
}
// Method three: profile something that you don't want to put into a closure
typealias ProfilingToken = String
var profilingMap: [ProfilingToken: (name: String, startTime: NSTimeInterval)] = [:]
func startProfiling(name: String) -> ProfilingToken {
let token = ProfilingToken(NSUUID().UUIDString)
profilingMap[token] = (name: name, startTime: NSDate().timeIntervalSince1970)
return token
}
func stopProfiling(profilingToken: ProfilingToken) {
let endTime = NSDate().timeIntervalSince1970
if let tuple = profilingMap[profilingToken] {
let time = endTime - tuple.startTime
print("Profiling: \(tuple.name) took \(Int(time * 1000)) ms")
}
}
// example:
let token = startProfiling("some statements I want to be able to move around easily")
func1()
func2()
func3()
func4()
func5()
stopProfiling(token)
// Method 3.5: simple method profiling with defer
func viewWillAppear() {
super.viewWillAppear()
let token = startProfiling("MyViewController#viewWillAppear")
defer { stopProfiling(token) }
// All your really,
// really,
// really,
// really...
// really long code goes here
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment