Skip to content

Instantly share code, notes, and snippets.

@sarah-j-smith
Created August 6, 2015 23:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sarah-j-smith/0e28a80388af02f2b64b to your computer and use it in GitHub Desktop.
Save sarah-j-smith/0e28a80388af02f2b64b to your computer and use it in GitHub Desktop.
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")
}
}
}
@sarah-j-smith
Copy link
Author

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