What is mach_absolute_time based on on iPhone

前端 未结 3 2001
忘掉有多难
忘掉有多难 2020-11-29 21:42

I use this code to keep track of last reboot:

+ (float) secondsSinceLastReboot{
     return ((float)(mach_absolute_time())) * ((float)timebase.numer) / ((flo         


        
相关标签:
3条回答
  • 2020-11-29 22:10

    Had some trouble with this myself. There isn't a lot of good documentation, so I went with experimentation. Here's what I was able to determine:

    mach_absolute_time depends on the processor of the device. It returns ticks since the device was last rebooted (otherwise known as uptime). In order to get it in a human readable form, you have to modify it by the result from mach_timebase_info (a ratio), which will return billionth of seconds (or nanoseconds). To make this more usable I use a function like the one below:

    #include <mach/mach_time.h>
    
    int getUptimeInMilliseconds()
    {
        const int64_t kOneMillion = 1000 * 1000;
        static mach_timebase_info_data_t s_timebase_info;
    
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            (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));
    }
    
    0 讨论(0)
  • 2020-11-29 22:16

    In case someone need it in Swift (works in 4.2 & 5.0).

    let beginTime = mach_absolute_time()
    
    // do something...
    
    var baseInfo = mach_timebase_info_data_t(numer: 0, denom: 0)
    if mach_timebase_info(&baseInfo) == KERN_SUCCESS {
        let finiTime = mach_absolute_time()
    
        let nano = (finiTime - beginTime) * UInt64(baseInfo.numer) / UInt64(baseInfo.denom)
    }
    
    0 讨论(0)
  • 2020-11-29 22:28

    If you don't care a lot about computation time you can use simple Obj-C class from Foundation

    NSTimeInterval systemUptime = [[NSProcessInfo processInfo] systemUptime];
    
    0 讨论(0)
提交回复
热议问题