Instantly share code, notes, and snippets.

Embed
What would you like to do?
import Darwin
enum Timebase {
private static let timebase: mach_timebase_info_data_t = {
var data = mach_timebase_info_data_t()
let ret = withUnsafeMutablePointer(&data, mach_timebase_info)
assert(ret == KERN_SUCCESS)
return data
}()
static func nsec(absoluteTime: UInt64) -> UInt {
return UInt(absoluteTime * UInt64(timebase.numer) / UInt64(timebase.denom))
}
}
/// Time the execution of the given `expr`.
func time<T>(@autoclosure expr: Void -> T) -> (nsec: UInt, value: T)
{
let start = mach_absolute_time()
let result = expr()
let delta = Timebase.nsec(mach_absolute_time() - start)
return (delta, result)
}
/// Evaluate `expr` `n` times and return the mean and sample standard deviation.
///
/// [Running mean/variance algorithm](https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Online_algorithm) due to Welford/Knuth.
func stats<T: IntegerType>(n: UInt, @autoclosure _ expr: Void -> T) -> (mean: Double, stdev: Double)
{
var mean: Double = 0
var variance: Double = 0
for i in 1...n {
let x = Double(expr().toIntMax())
let delta = x - mean
mean += delta / Double(i)
variance += delta*(x - mean)
}
return (mean, sqrt(variance/Double(n - 1)))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment