I'm looking for a way to get an absolute, always-incrementing system uptime on iOS.
It should return the time since the device was last rebooted, and not be affected by changes to the system date.
All the methods I can find either pause when the device is asleep (CACurrentMediaTime
, [NSProcessInfo systemUptime]
, mach_absolute_time
) or are changed when the system date changes (sysctl/KERN_BOOTTIME
).
Any ideas?
As said in one of the comments, POSIX's
clock_gettime()
was implemented in iOS 10 and macOS 10.12. When used with theCLOCK_MONOTONIC
argument, it does seem to return the uptime value. However, this is not guaranteed by the documentation:And an extract from the corresponding macOS man page:
Note that
CLOCK_MONOTONIC
returns with microsecond precision whileCLOCK_MONOTONIC_RAW
with nanosecond precision.Swift code:
For those still interested in getting the kernel's boot time in Swift:
I think I worked it out.
time()
carries on incrementing while the device is asleep, but of course can be manipulated by the operating system or user. However, the Kernel boottime (a timestamp of when the system last booted) also changes when the system clock is changed, therefore even though both these values are not fixed, the offset between them is.I'd comment on Leszek's answer, but not enough rep... Leszek's solution returns seconds.
The following is a modified version of Leszek's answer if anyone needs millisecond precision.
There's a race condition in all examples listed: if there's a time change (NTP or user-modified), the code will race and the clock is no longer monotonic.
The correct implementation is:
If higher precision is needed then below is a modified version of accepted answer.
Why not using systemUptime?
systemUptime Returns how long it has been since the computer has been restarted.
Availability Available in iOS 4.0 and later. Declared In NSProcessInfo.h
I have tested and proved that at least on iPhone 5 with iOS 7.1.1, systemUptime DOES NOT STOP when your phone is locked. So anyone don't believe this can test it yourself.