Skip to content

Instantly share code, notes, and snippets.

@nyg
Last active April 1, 2024 21:35
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nyg/d81308a92fbf7e9c44c5f72db5ee2171 to your computer and use it in GitHub Desktop.
Save nyg/d81308a92fbf7e9c44c5f72db5ee2171 to your computer and use it in GitHub Desktop.
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