I'm trying to get uptime for iOS. I was using mach_absolute_time - but I found that it paused during sleep.
I found this snippet:
- (time_t)uptime
{
struct timeval boottime;
int mib[2] = {CTL_KERN, KERN_BOOTTIME};
size_t size = sizeof(boottime);
time_t now;
time_t uptime = -1;
(void)time(&now);
if (sysctl(mib, 2, &boottime, &size, NULL, 0) != -1 && boottime.tv_sec != 0)
{
uptime = now - boottime.tv_sec;
}
return uptime;
}
It does the trick. BUT, it's returning whole seconds. Any way to get milliseconds out of this?
If you want something pure Objective-C, try
(
NSTimeInterval
is a typedef fordouble
, representing seconds.)The kernel does not (apparently) store a higher-resolution timestamp of its boot time.
KERN_BOOTTIME
is implemented by thesysctl_boottime
function inbsd/kern/kern_sysctl.c
. It callsboottime_sec
.boottime_sec
is implemented inbsd/kern/kern_time.c
. It callsclock_get_boottime_nanotime
, which has a promising name.clock_get_boottime_nanotime
is implemented inosfmk/kern/clock.c
. It is hard-coded to always return 0 in itsnanosecs
argument.I know it's probably too late, but there you go: