ios - iOS 启动时间会漂移吗?

标签 ios time unix-timestamp

我正在使用此代码来确定我的 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;

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

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

最佳答案

虽然 iOS 内核是闭源的,但有理由假设其中大部分与 OSX 内核相同,即 open-source .

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);
}

clock_boottime声明为:

static uint64_t     clock_boottime;             /* Seconds boottime epoch */

最后这个函数的注释表明它确实可以改变:

/*
 *  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)
{
    ...

更新以回答来自 OP 的查询

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

$ find . -type f -exec grep -l clock_set_calendar_microtime {} \;

关于ios - iOS 启动时间会漂移吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30237715/

相关文章:

mysql - 选择日期戳在过去 24 小时内的所有不同值,并按总行数 ASC 排序

ios - SwiftyJSON - 可以检查对象类型吗?

ios - 如何获取表格单元格中的标签以继续到下一行而不是被切断屏幕? (Xcode 8)

javascript - 将 Unix 时间戳转换为可读格式,在 JavaScript 代码中不起作用

php - 如何计算两个日期之间的天数?

c - 泊松到达分布函数并跟踪它

xcode - 通用应用程序 - iPad View 加载,但我无法将任何 ImageView 链接到 UIImage 对象而不会出现错误

ios - 如何从连续的 URL 中获取数据

javascript - 比较 JavaScript 中的日期和时间

sql - 在 PostgreSQL 中根据时间更新行