28
27

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Swiftで実行時間計測

Last updated at Posted at 2015-10-06

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?

28
27
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
28
27

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?