Last active
August 29, 2015 14:25
-
-
Save jtbandes/4feadf4ec4ab89ff7940 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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