Created
August 6, 2015 23:05
-
-
Save sarah-j-smith/0e28a80388af02f2b64b to your computer and use it in GitHub Desktop.
Time Profiling in Swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// PerformanceTimer.swift | |
// WordMonsters | |
// | |
// Created by Sarah Smith on 8/6/15. | |
// Copyright (c) 2015 Sarah Smith. All rights reserved. | |
// | |
import Foundation | |
class PerformanceTimer { | |
static let instance = PerformanceTimer() | |
class func addRecord( recordText: String ) { | |
PerformanceTimer.instance.addTimeRecord(recordText) | |
} | |
class func print() { | |
PerformanceTimer.instance.printTimeRecords() | |
} | |
typealias TimerRecord = ( timerName: String, timeStamp: Double ) | |
var records : [ TimerRecord ] | |
init() { | |
records = [] | |
} | |
func addTimeRecord( recordText: String ) { | |
let timeValue = CACurrentMediaTime() | |
records.append(timerName: recordText, timeStamp: timeValue) | |
} | |
func printTimeRecords() { | |
println("Time stamps:") | |
if records.count > 1 { | |
let baseline = records.first!.timeStamp | |
for rec in records { | |
println(" \(rec.timerName) - \(rec.timeStamp - baseline)") | |
} | |
records = [] | |
} | |
else | |
{ | |
println("Not enough time stamps recorded") | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add records with the static
addRecord()
Because there's a singleton which resets each time you call theprint()
function, you can log records to the PerformanceTimer from anywhere in the code. When you want to trigger a report, e.g. by touching the screen, call thatprint()
method.Use it like:
In some other file:
Then: