2017/10/04 - Swift4での動作確認済み
#この記事について
関数の実行時間を求めるのにいちいち
let start = NSDate()
// someMethod
let timeElapsed = -startTime.timeIntervalSinceNow
print(timeElapsed)
などと毎回書いていくのがめんどくさかったので調べてみました。
#1. タイトル付きで表示
func printTimeElapsedWhenRunningCode <T> (title: String, operation: @autoclosure () -> T) {
let startTime = CFAbsoluteTimeGetCurrent()
operation()
let timeElapsed = CFAbsoluteTimeGetCurrent() - startTime
print("Time elapsed for \(title): \(timeElapsed) seconds")
}
##使い方
以下のような関数があるとしたら、
func isEven(x: Int) -> Bool {
return x % 2 == 0
}
printTimeElapsedWhenRunningCode("isEven", operation: isEven(1))
// Time elapsed for isEven: 0.000578999519348145 seconds
#2. 返り値が実行時間
func timeElapsedInSecondsWhenRunningCode <T> (operation: @autoclosure () -> T) -> Double {
let startTime = CFAbsoluteTimeGetCurrent()
operation()
let timeElapsed = CFAbsoluteTimeGetCurrent() - startTime
return Double(timeElapsed)
}
##使い方
print(timeElapsedInSecondsWhenRunningCode(isEven(1)))
// 0.000547945499420166
#3.1 関数の返り値と実行時間のメッセージ
func measure <T> (_ f: @autoclosure () -> T) -> (result: T, duration: String) {
let startTime = CFAbsoluteTimeGetCurrent()
let result = f()
let timeElapsed = CFAbsoluteTimeGetCurrent() - startTime
return (result, "Elapsed time is \(timeElapsed) seconds.")
}
##使い方
print(measure(isEven(1)))
// (false, "Elapsed time is 0.000652015209197998 seconds.")
print(measure(isEven(1)).result)
// false
print(measure(isEven(1)).duration)
// Elapsed time is 0.000642001628875732 seconds.
#3.2 関数の返り値と実行時間
func measure <T> (_ f: @autoclosure () -> T) -> (result: T, duration: Double) {
let startTime = CFAbsoluteTimeGetCurrent()
let result = f()
let timeElapsed = CFAbsoluteTimeGetCurrent() - startTime
return (result, Double(timeElapsed))
}
##使い方
print(measure(isEven(1)))
// (false, 0.000528991222381592)
print(measure(isEven(1)).result)
// false
print(measure(isEven(1)).duration)
// 0.000581979751586914
#おわりに
お好みのものが見つかれば幸いです。
#参考
How to log a method's execution time exactly in milliseconds?
Measure elapsed time in swift
How to benchmark Swift code execution?