Last active
June 25, 2020 06:52
-
-
Save pchelnikov/33fb9e1f6f047f555b41 to your computer and use it in GitHub Desktop.
iOS System Uptime
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
static func systemUptime() -> TimeInterval { | |
var currentTime = time_t() | |
var bootTime = timeval() | |
var mib = [CTL_KERN, KERN_BOOTTIME] | |
// NOTE: Use strideof(), NOT sizeof() to account for data structure | |
// alignment (padding) | |
// http://stackoverflow.com/a/27640066 | |
// https://devforums.apple.com/message/1086617#1086617 | |
var size = MemoryLayout<timeval>.stride | |
let result = sysctl(&mib, u_int(mib.count), &bootTime, &size, nil, 0) | |
if result != 0 { | |
#if DEBUG | |
print("ERROR - \(#file):\(#function) - errno = " | |
+ "\(result)") | |
#endif | |
return 0 | |
} | |
// Since we don't need anything more than second level accuracy, we use | |
// time() rather than say gettimeofday(), or something else. uptime | |
// command does the same | |
time(¤tTime) | |
let uptime = currentTime - bootTime.tv_sec | |
return TimeInterval(uptime) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment