Skip to content

Instantly share code, notes, and snippets.

@nyg
Last active January 31, 2020 05:01
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Embed
What would you like to do?
Get boot time and uptime for macOS & iOS
// https://stackoverflow.com/a/45068046/5536516
import Foundation
func kernelBootTime() -> timeval {
var mib = [ CTL_KERN, KERN_BOOTTIME ]
var bootTime = timeval()
var bootTimeSize = MemoryLayout<timeval>.size
if 0 != sysctl(&mib, UInt32(mib.count), &bootTime, &bootTimeSize, nil, 0) {
fatalError("Could not get boot time, errno: \(errno)")
}
return bootTime
}
func uptime() -> timespec {
var uptime = timespec()
if 0 != clock_gettime(CLOCK_MONOTONIC_RAW, &uptime) {
fatalError("Could not execute clock_gettime, errno: \(errno)")
}
return uptime
}
print(kernelBootTime()) // timeval(tv_sec: 1499259206, tv_usec: 122778)
print(uptime()) // timespec(tv_sec: 636705, tv_nsec: 750700397)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment