Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Time Profiling in Swift
//
// 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")
}
}
}
Owner

Add records with the static addRecord() Because there's a singleton which resets each time you call the print() 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 that print() method.

Use it like:

override func didMoveToView(view: SKView)
{
    PerformanceTimer.addRecord("Game Scene didMoveToView start")

    physicsWorld.contactDelegate = self
    physicsWorld.gravity = CGVector.zeroVector

    SKAction.afterDelay(0.2, runBlock: { () -> Void in
        SKTAudio.sharedInstance().playBackgroundMusic("Ouroboros.aifc")
    })

    PerformanceTimer.addRecord("Scheduled music")
    setupGameplay()
    PerformanceTimer.addRecord("Setup Gameplay")
    setupUI()

    launchpad.targetMissileAt(monsterManager.activeMonsters.first!)

    PerformanceTimer.addRecord("Game Scene didMoveToView end")
}

In some other file:

func targetMissileAt(monster: Monster) {
    // more code
    PerformanceTimer.addRecord("targetMissileAt")
    // more code
}

Then:

    override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
    /* Called when a touch begins */

    for touch in (touches as! Set<UITouch>) {
        let location = touch.locationInNode(self)

        keyboard.checkKeyPress(location)

        PerformanceTimer.print()
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment