iOS 启动时间会漂移吗?

Pau*_*nne 4 time unix-timestamp ios

我使用此代码来确定我的 iOS 设备上次重新启动的时间:

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) {
    return boottime.tv_sec;
}

return 0;
Run Code Online (Sandbox Code Playgroud)

这次我发现了一些异常现象。特别是,我保存了 long 以及几天和几周后,检查保存的 long 与上述代码返回的值。

我不确定,但我想我看到了一些偏差。这对我来说没有任何意义。我不会转换为 NSDate 以防止漂移。我认为启动时间是由内核在启动时记录的,并且不会再次计算,它只是被存储。但是,iOS 是否可以像 NSDate 那样节省启动时间,同时存在任何固有的漂移问题?

tro*_*foe 5

虽然 iOS 内核是闭源的,但可以合理地假设它的大部分与开源的OSX 内核相同。

里面osfmk/kern/clock.c有这个函数:

/*
 *  clock_get_boottime_nanotime:
 *
 *  Return the boottime, used by sysctl.
 */
void
clock_get_boottime_nanotime(
    clock_sec_t         *secs,
    clock_nsec_t        *nanosecs)
{
    spl_t   s;

    s = splclock();
    clock_lock();

    *secs = (clock_sec_t)clock_boottime;
    *nanosecs = 0;

    clock_unlock();
    splx(s);
}
Run Code Online (Sandbox Code Playgroud)

clock_boottime声明为:

static uint64_t     clock_boottime;             /* Seconds boottime epoch */
Run Code Online (Sandbox Code Playgroud)

最后,对该函数的注释表明它确实可以更改:

/*
 *  clock_set_calendar_microtime:
 *
 *  Sets the current calendar value by
 *  recalculating the epoch and offset
 *  from the system clock.
 *
 *  Also adjusts the boottime to keep the
 *  value consistent, writes the new
 *  calendar value to the platform clock,
 *  and sends calendar change notifications.
 */
void
clock_set_calendar_microtime(
    clock_sec_t         secs,
    clock_usec_t        microsecs)
{
    ...
Run Code Online (Sandbox Code Playgroud)

更新以回答 OP 的查询

我不确定clock_set_calendar_microtime()调用的频率,因为我不熟悉内核的内部工作原理;但是它会调整clock_boottime值并且该clock_bootime值在 中初始化clock_initialize_calendar(),所以我想说它可以被多次调用。我无法使用以下方法找到对它的任何调用:

$ find . -type f -exec grep -l clock_set_calendar_microtime {} \;
Run Code Online (Sandbox Code Playgroud)