正常运行时间iOS Objective C – 毫秒精度
我正在试图让iOS的正常运行。 我正在使用mach_absolute_time – 但我发现它在睡眠中暂停。
我发现这个片段:
- (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; }
它的窍门。 但是,它正在返回整秒。 任何方式来得到这个毫秒?
谢谢!
内核不(显然)存储引导时间的更高分辨率的时间戳。
KERN_BOOTTIME
由bsd/kern/kern_sysctl.c
的sysctl_boottime
函数实现。 它调用boottime_sec
。
boottime_sec
在bsd/kern/kern_time.c
。 它调用clock_get_boottime_nanotime
,这个名字很有希望。
clock_get_boottime_nanotime
在osfmk/kern/clock.c
。 它是硬编码的,在其nanosecs
参数中始终返回0。
如果你想要一些纯粹的Objective-C,请尝试
NSTimeInterval uptime = [[NSProcessInfo processInfo] systemUptime];
( NSTimeInterval
是double
的typedef,代表秒。)
我知道这可能太晚了,但你去了:
+ (NSTimeInterval)uptime { struct timeval boottime; int mib[2] = {CTL_KERN, KERN_BOOTTIME}; size_t size = sizeof(boottime); struct timeval now; struct timezone tz; gettimeofday(&now, &tz); double uptime = -1; if (sysctl(mib, 2, &boottime, &size, NULL, 0) != -1 && boottime.tv_sec != 0) { uptime = now.tv_sec - boottime.tv_sec; uptime += (double)(now.tv_usec - boottime.tv_usec) / 1000000.0; } return uptime; }