6

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?

voromax
  • 3,369
  • 2
  • 30
  • 53

3 Answers3

19

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

[[NSProcessInfo processInfo] systemUptime]

Gabe Sechan
  • 90,003
  • 9
  • 87
  • 127
uchuugaka
  • 12,679
  • 6
  • 37
  • 55
  • You found it and therefore you deserve a prize! The correct answer is yours. But... there is a typo in the method name: `systemUptime` – voromax Jul 16 '13 at 17:05
  • 2
    This does not have to be the time since boot, documentation says: The amount of time the system has been awake since the last time it was restarted. On iOS 10 beta at least it seems to not add the time in was asleep. – Jens Åkerblom Sep 12 '16 at 13:58
1

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

malex
  • 9,874
  • 3
  • 56
  • 77
-1

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.

David Neiss
  • 8,161
  • 2
  • 20
  • 21
  • As I supposed there is no possibilities to make system calls in iOS. But by now I found one more solution - mach_absolute_time which needs to be converted – voromax May 09 '11 at 19:32
  • No, you can certainly make system calls in iOS. You can write in straight C. – David Neiss May 09 '11 at 20:30
  • Yes... There is a system() function in iOS but lot of commands are not available. And this is not a best way to get the double value in seconds from the last device boot. I found some additional info about mach_absolute_time [on this post](http://stackoverflow.com/questions/1450737/what-is-mach-absolute-time-based-on-on-iphone) but I am still wondering if lots of things (Core Animation, AVFoundation, UIAccelerometer, etc) in iOS are based on this clock, there is no simple common method to get this time – voromax May 09 '11 at 22:10
  • @voromax, you can directly call [`times` function](http://pubs.opengroup.org/onlinepubs/9699919799/functions/times.html) in Objective-C or Swift. – Franklin Yu May 26 '16 at 02:11