-
-
Save vixvix/0c231453e765ca17e7e9788aeab17f12 to your computer and use it in GitHub Desktop.
simple nanosecond timer using mach_absolute_time
This file contains hidden or 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
/* | |
var t = Timer() | |
t.start() | |
// do something | |
t.stop() | |
print("took \(t.seconds)") | |
*/ | |
import Darwin | |
struct Timer { | |
var startTime: UInt64 = 0 | |
var stopTime: UInt64 = 0 | |
let numer: UInt64 | |
let denom: UInt64 | |
init() { | |
var info = mach_timebase_info(numer: 0, denom: 0) | |
mach_timebase_info(&info) | |
numer = UInt64(info.numer) | |
denom = UInt64(info.denom) | |
} | |
mutating func start() { | |
startTime = mach_absolute_time() | |
} | |
mutating func stop() { | |
stopTime = mach_absolute_time() | |
} | |
var nanoseconds: UInt64 { | |
return ((stopTime - startTime) * numer) / 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