Last active
August 29, 2015 14:08
-
-
Save tadyjp/01cb019d84ed976652f8 to your computer and use it in GitHub Desktop.
Swiftで重い処理の処理時間を測定する ref: http://qiita.com/tady/items/40d7c4feecda337cf271
This file contains hidden or 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
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() | |
} | |
} | |
This file contains hidden or 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
Benchmark.measure("重いかもしれない処理1", block: { | |
sleep(1) | |
return | |
}) | |
// => "Benchmark: 重いかもしれない処理1, Elasped time: 1.023(s)" |
This file contains hidden or 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
// 生成に時間が掛かる重いクラス | |
class MyHeavyClass { | |
init() { | |
sleep(1) | |
} | |
func myMethod() { | |
} | |
} | |
Benchmark.measure("重いかもしれない処理2", block: { | |
let myHeavyValue = MyHeavyClass() | |
}) | |
myHeavyValue.myMethod() | |
// => Use of unresolved identifier 'myHeavyValue' |
This file contains hidden or 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
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