Skip to content

Instantly share code, notes, and snippets.

@kazk
Last active August 29, 2015 14:15
Show Gist options
  • Save kazk/6ec84cc80bb8558cbf55 to your computer and use it in GitHub Desktop.
Save kazk/6ec84cc80bb8558cbf55 to your computer and use it in GitHub Desktop.
import Darwin
// import Darwin.Mach.mach_time // (mach_timebase_info, mach_absolute_time)
// import Darwin.Mach.clock_types // (NSEC_PER_*)
public func timeBlockNSec(block: ()->()) -> Double { // in nanoseconds
var info = mach_timebase_info(numer: 0, denom: 0)
let kr = mach_timebase_info(&info)
if kr != KERN_SUCCESS {
fatalError("Initialization of `mach_timebase_info` failed with code \(kr).")
}
if info.denom == 0 {
fatalError("Initialized `mach_timebase_info` contains invalid value.")
}
let scale = Double(info.numer)/Double(info.denom)
let start = mach_absolute_time()
block()
let end = mach_absolute_time()
let delta = Double(end - start)
return delta * scale
}
public func timeBlockUSec(block: ()->()) -> Double { // in microseconds
return timeBlockNSec(block)/Double(NSEC_PER_USEC)
}
public func timeBlockMSec(block: ()->()) -> Double { // in milliseconds
return timeBlockNSec(block)/Double(NSEC_PER_MSEC)
}
public func timeBlock(block: ()->()) -> Double { // in seconds
return timeBlockNSec(block)/Double(NSEC_PER_SEC)
}
// Resources:
// http://www.bignerdranch.com/blog/a-timing-utility/
// https://gist.github.com/bignerdranch/2006587
// https://developer.apple.com/library/mac/qa/qa1398/_index.html
// https://developer.apple.com/library/ios/qa/qa1643/_index.html
// https://developer.apple.com/library/mac/samplecode/CoreAudioUtilityClasses/Listings/CoreAudio_PublicUtility_CAHostTimeBase_cpp.html
// ClockFrequency: (Double(info.numer)/Double(info.denom)) * Double(NSEC_PER_SEC)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment