How to get NSTimeInterval value from last boot

白昼怎懂夜的黑 提交于 2019-12-07 11:38:48

问题


I need to get NSTimeInterval value from last device boot. I found CACurrentMediaTime() which suits this task, but in my app I am not using Core Animation and I don't think that this is the best way to include this framework just to get this function. Is there another way to get time in seconds from last boot more elegant way?


回答1:


The NSTimeInterval value since the last system restart can be acquired more directly via the following Foundation object and method:

[[NSProcessInfo processInfo] systemUptime]




回答2:


The fastest low-level method is to read system uptime from processor using mach_absolute_time()

#include <mach/mach_time.h>

int systemUptime()
{
    static float timebase_ratio;

    if (timebase_ratio == 0) {
       mach_timebase_info_data_t s_timebase_info;
       (void) mach_timebase_info(&s_timebase_info);

       timebase_ratio = (float)s_timebase_info.numer / s_timebase_info.denom;
    }

    return (int)(timebase_ratio * mach_absolute_time() / 1000000000);
}

Note that timebase_ratio is different for processors. For example, on macbook it equals 1 whereas on iPhone 5 it equals 125/3 (~40).




回答3:


Try a C system call, times(3) is supposed to return uptime.

On MacOSX, uptime also returns such. So there has to be a way though that as well.



来源:https://stackoverflow.com/questions/5937564/how-to-get-nstimeinterval-value-from-last-boot

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!