Get the precise time of system bootup on iOS/OS X
In OSX you could use sysctl(). This is how the OSX Unix utility uptime
does it. Source code is available - search for boottime
.
Fair warning though, in iOS i have no idea if this would work.
UPDATE: found some code :)
#include <sys/types.h>
#include <sys/sysctl.h>
#define MIB_SIZE 2
int mib[MIB_SIZE];
size_t size;
struct timeval boottime;
mib[0] = CTL_KERN;
mib[1] = KERN_BOOTTIME;
size = sizeof(boottime);
if (sysctl(mib, MIB_SIZE, &boottime, &size, NULL, 0) != -1)
{
// successful call
NSDate* bootDate = [NSDate dateWithTimeIntervalSince1970:
boottime.tv_sec + boottime.tv_usec / 1.e6];
}
see if this works...
The accepted answer, using systcl
, works, but the values returned by sysctl
for KERN_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
and CALENDAR_CLOCK
, they sometimes differ by a couple seconds, so its not clear whether the KERN_BOOTTIME
value corresponds exactly to the time-basis for the uptime clocks.