本文介绍了获取iOS / OS X上系统启动的准确时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

是否有API来获取表示系统启动时间的 NSDate NSTimeInterval ?某些API,例如 [NSProcessInfo systemUptime] 和Core Motion自启动后返回时间。我需要将这些正常运行时间值与 NSDate 精确地关联到大约一毫秒。

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 NSDates, to about a millisecond.

自引导以来表面上提供的时间更精确,但很容易看出 NSDate 已经提供了大约100纳秒的精度,而微秒以下的任何东西只是测量中断延迟和PCB时钟抖动。

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.

显而易见的是从当前时间 [NSDate date] 中减去正常运行时间。但是假设两个系统调用之间的时间没有变化,这很难实现。此外,如果线程在调用之间被抢占,则一切都被抛弃。解决方法是多次重复该过程并使用最小的结果,但是很糟糕。

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 必须有一个它用于从系统正常运行时间生成具有当前时间的对象的主偏移,是否真的没有办法获得它?

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?

推荐答案

在OSX中,您可以使用。这就是OSX Unix实用程序正常运行时间的功能。 可用 - 搜索启动时间

In OSX you could use sysctl(). This is how the OSX Unix utility uptime does it. Source code is available - search for boottime.

虽然公平警告,在iOS中我不知道这是否有效。

Fair warning though, in iOS i have no idea if this would work.

更新:找到了一些代码:)

#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...

这篇关于获取iOS / OS X上系统启动的准确时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-07 00:21