Is there an API to obtain the NSDate
or NSTimeInterval
representing the time the system booted? Some APIs such as [NSProcessInfo systemUptime]
and Core Motion return time since boot. I need to precisely correlate these uptime values with NSDate
s, to about a millisecond.
Time since boot ostensibly provides more precision, but it's easy to see that NSDate
already provides precision on the order of 100 nanoseconds, and anything under a microsecond is just measuring interrupt latency and PCB clock jitter.
The obvious thing is to subtract the uptime from the current time [NSDate date]
. But that assumes that time does not change between the two system calls, which is, well, hard to accomplish. Moreover if the thread is preempted between the calls, everything is thrown off. The workaround is to repeat the process several times and use the smallest result, but yuck.
NSDate
must have a master offset it uses to generate objects with the current time from the system uptime, is there really no way to obtain it?
Refer to this category
NSDate+BootTime.h
NSDate+BootTime.m
There is another way. It could give result slightly different (less or more) than accepted answer
I have compared them. I get difference -7 second for OSX 10.9.3 and +2 second for iOS 7.1.1
As i understand this way gives same result if wall clock changed, but accepted answer gives different results if wall clock changed...
Here code:
The routines inside mach/mach_time.h are guaranteed to be monotonically increasing, unlike NSDate.
In OSX you could use sysctl(). This is how the OSX Unix utility
uptime
does it. Source code is available - search forboottime
.Fair warning though, in iOS i have no idea if this would work.
UPDATE: found some code :)
see if this works...
The accepted answer, using
systcl
, works, but the values returned bysysctl
forKERN_BOOTTIME
, at least in my testing (Darwin Kernel Version 11.4.2), are always in whole seconds (the microseconds field,tv_usec
, is 0). This means the resulting time may be up to 1 second off, which is not very accurate.Also, having compared that value, to one derived experimentally from the difference between the
REALTIME_CLOCK
andCALENDAR_CLOCK
, they sometimes differ by a couple seconds, so its not clear whether theKERN_BOOTTIME
value corresponds exactly to the time-basis for the uptime clocks.