Skip to content

Instantly share code, notes, and snippets.

@naru-jpn
Created November 29, 2021 07:55
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save naru-jpn/f823f139eba4f42b2cc680ecb6db86c5 to your computer and use it in GitHub Desktop.
Save naru-jpn/f823f139eba4f42b2cc680ecb6db86c5 to your computer and use it in GitHub Desktop.
Swiftプログラムの実行時間の計測 平均や標準偏差の計算
import Accelerate
class TimeProfiler {
private var results: [Float] = []
private var samples: Int = 0
private let ignores: Int
/// 現在の試行回数
var trials: Int {
results.count
}
/// 平均
var mean: Float {
vDSP.mean(results)
}
/// 標準偏差
var standardDeviation: Float {
let mean = vDSP.mean(results)
let meanSquare = vDSP.meanSquare(results)
let count = results.count
return sqrt(meanSquare - mean * mean) * sqrt(Float(count) / Float(count - 1))
}
/// 最初の ignores 回分の測定を無視する場合は値を指定してください
init(ignores: Int = 0) {
self.ignores = ignores
}
/// 試行
func trial<U>(procedure: () -> (U)) -> U {
let start = mach_absolute_time()
let result = procedure()
let end = mach_absolute_time()
if samples >= ignores {
results.append(nanoElapsed(start: start, end: end))
}
samples += 1
return result
}
/// 試行
func trial<T, U>(input: T, procedure: ((T) -> (U))) -> U {
let start = mach_absolute_time()
let result = procedure(input)
let end = mach_absolute_time()
if samples >= ignores {
results.append(nanoElapsed(start: start, end: end))
}
samples += 1
return result
}
/// 測定のリセット
func reset() {
results = []
samples = 0
}
private func nanoElapsed(start: UInt64, end: UInt64) -> Float {
var timebaseInfo = mach_timebase_info_data_t()
mach_timebase_info(&timebaseInfo)
return Float((end - start) * UInt64(timebaseInfo.numer) / UInt64(timebaseInfo.denom))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment