Get boot time and uptime for macOS & iOS
This file contains 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
// 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