Skip to content

Instantly share code, notes, and snippets.

@dsheets
Forked from jstn/Timer.swift
Last active August 12, 2016 18:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dsheets/f316b6f7d0edbdedaa4007e2f04471df to your computer and use it in GitHub Desktop.
Save dsheets/f316b6f7d0edbdedaa4007e2f04471df to your computer and use it in GitHub Desktop.
simple nanosecond timer using mach_absolute_time
/*
var t = Timer()
t.start()
// do something
t.stop()
println("took \(t.seconds)")
*/
import Darwin
struct Timer {
static var b: mach_timebase_info = mach_timebase_info(numer: 0, denom: 0)
var startTime: UInt64 = 0
var stopTime: UInt64 = 0
init() {
mach_timebase_info(&Timer.b)
}
mutating func start() {
startTime = mach_absolute_time()
}
mutating func stop() {
stopTime = mach_absolute_time()
}
var nanoseconds: UInt64 {
let elapsed = stopTime - startTime
return elapsed * UInt64(Timer.b.numer) / UInt64(Timer.b.denom)
}
var milliseconds: Double {
return Double(nanoseconds) / 1_000_000
}
var seconds: Double {
return Double(nanoseconds) / 1_000_000_000
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment