Skip to content

Instantly share code, notes, and snippets.

@tadyjp
Last active August 29, 2015 14:08
Show Gist options
  • Save tadyjp/01cb019d84ed976652f8 to your computer and use it in GitHub Desktop.
Save tadyjp/01cb019d84ed976652f8 to your computer and use it in GitHub Desktop.
Swiftで重い処理の処理時間を測定する ref: http://qiita.com/tady/items/40d7c4feecda337cf271
import Foundation
class Benchmark {
// 開始時刻を保存する変数
var startTime: NSDate
var key: String
// 処理開始
init(key: String) {
self.startTime = NSDate()
self.key = key
}
// 処理終了
func finish() {
let elapsed = NSDate().timeIntervalSinceDate(self.startTime) as Double
let formatedElapsed = String(format: "%.3f", elapsed)
println("Benchmark: \(key), Elasped time: \(formatedElapsed)(s)")
}
// 処理をブロックで受け取る
class func measure(key: String, block: () -> ()) {
let benchmark = Benchmark(key: key)
block()
benchmark.finish()
}
}
Benchmark.measure("重いかもしれない処理1", block: {
sleep(1)
return
})
// => "Benchmark: 重いかもしれない処理1, Elasped time: 1.023(s)"
// 生成に時間が掛かる重いクラス
class MyHeavyClass {
init() {
sleep(1)
}
func myMethod() {
}
}
Benchmark.measure("重いかもしれない処理2", block: {
let myHeavyValue = MyHeavyClass()
})
myHeavyValue.myMethod()
// => Use of unresolved identifier 'myHeavyValue'
let myBenchMark = Benchmark(key: "重いかもしれない処理2")
let myHeavyValue = MyHeavyClass()
myBenchMark.finish()
// => "Benchmark: 重いかもしれない処理2, Elasped time: 1.025(s)"
myHeavyValue.myMethod()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment