简体   繁体   English

正常运行时间iOS Objective-C - 毫秒级精度

[英]Uptime iOS Objective-C - millisecond precision

I'm trying to get uptime for iOS. 我正试图让iOS的正常运行时间。 I was using mach_absolute_time - but I found that it paused during sleep. 我正在使用mach_absolute_time - 但我发现它在睡眠时暂停了。

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? 有什么方法可以获得毫秒数?

The kernel does not (apparently) store a higher-resolution timestamp of its boot time. 内核(显然)不会存储其启动时间的更高分辨率时间戳。

KERN_BOOTTIME is implemented by the sysctl_boottime function in bsd/kern/kern_sysctl.c . KERN_BOOTTIMEbsd/kern/kern_sysctl.csysctl_boottime函数实现。 It calls boottime_sec . 它调用boottime_sec

boottime_sec is implemented in bsd/kern/kern_time.c . boottime_secbsd/kern/kern_time.c It calls clock_get_boottime_nanotime , which has a promising name. 它调用clock_get_boottime_nanotime ,它有一个很有希望的名字。

clock_get_boottime_nanotime is implemented in osfmk/kern/clock.c . clock_get_boottime_nanotimeosfmk/kern/clock.c It is hard-coded to always return 0 in its nanosecs argument. 硬编码总是在nanosecs参数中返回0。

If you want something pure Objective-C, try 如果你想要纯粹的Objective-C,试试吧

NSTimeInterval uptime = [[NSProcessInfo processInfo] systemUptime];

( NSTimeInterval is a typedef for double , representing seconds.) NSTimeIntervaldouble的typedef,表示秒。)

I know it's probably too late, but there you go: 我知道这可能为时已晚,但你去了:

+ (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;
} 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM