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