Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get NSTimeInterval value from last boot

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?

like image 289
voromax Avatar asked May 09 '11 13:05

voromax


2 Answers

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

[[NSProcessInfo processInfo] systemUptime]

like image 88
uchuugaka Avatar answered Sep 24 '22 06:09

uchuugaka


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

like image 31
malex Avatar answered Sep 20 '22 06:09

malex