#includeint getUptimeInMilliseconds(){ const int64_t kOneMillion = 1000 * 1000; static mach_timebase_info_data_t s_timebase_info; if (s_timebase_info.denom == 0) { (void) mach_timebase_info(&s_timebase_info); } // mach_absolute_time() returns billionth of seconds, // so divide by one million to get milliseconds return (int)((mach_absolute_time() * s_timebase_info.numer) / (kOneMillion * s_timebase_info.denom));}
但是这个方法使用的人不多,原因在于,如果系统处于休眠状态,那么这个值也是停止的,所以它本质是进程运行的时钟计数器(run()
),而非整个系统的(run() + sleep()
)时钟计数器。这样严格来说,是完全不准确的数据,不可用。
这个较为多的使用场景是作为耗时的测量函数,比如在某个时间获取mach_absolute_time
作为startTime,间隔一定时间之后再次获取mach_absolute_time
作为endTime,然后差值可以作为这个阶段的耗时,这样的使用场景较多。
-
stackoverflow:有人问这个
mach_absolute_time
的真正含义,因为他发现自己的设备并没有重启,但是基于mach_absolute_time
算出来的时间,自己的设备在某一时刻重启过,所以对这个东西"一脸懵逼"... -
Apple 官方对某个开发者的提问What time units does it use?进行的回复.