LoginSignup
46
43

More than 5 years have passed since last update.

Swiftで重い処理の処理時間を測定する

Last updated at Posted at 2014-11-01

概要

Swiftでも、rubyのBenchmarkのように簡単に処理時間を計算するメソッドを書いた。
このメソッドを使うと、アプリの速度改善に役立つ。

Benchmarkクラス

Benchmark.swift

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()
  }
}

使い方

1. ブロックを渡す場合

Sample1.swift
Benchmark.measure("重いかもしれない処理1", block: {
  sleep(1)
  return
})

// => "Benchmark: 重いかもしれない処理1, Elasped time: 1.023(s)"

2. インスタンスを使う場合

基本的には「1」の使い方でいいが、測定したい部分(blockの中)で定義した変数はそのブロックから出ると使えなくなってしまう。

Sample2-NG.swift
// 生成に時間が掛かる重いクラス
class MyHeavyClass {
  init() {
    sleep(1)
  }

  func myMethod() {
  }
}

Benchmark.measure("重いかもしれない処理2", block: {
  let myHeavyValue = MyHeavyClass()
})

myHeavyValue.myMethod()
// => Use of unresolved identifier 'myHeavyValue'

その場合は以下の方法を使う。

Sample2-OK.swift
let myBenchMark = Benchmark(key: "重いかもしれない処理2")
let myHeavyValue = MyHeavyClass()
myBenchMark.finish()
// => "Benchmark: 重いかもしれない処理2, Elasped time: 1.025(s)"

myHeavyValue.myMethod()

ソースコード

https://github.com/tadyjp/BenchMark.playground
ここからダウンロードして試せます。

参考

46
43
0

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
46
43