Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
477 views
in Technique[技术] by (71.8m points)

timer - What is mach_absolute_time based on on iPhone

I use this code to keep track of last reboot:

+ (float) secondsSinceLastReboot{
     return ((float)(mach_absolute_time())) * ((float)timebase.numer) / ((float)timebase.denom) / 1000000000.0f;
}

I assumed mach_absolute_time() was based on last device boot time like it is on a mac. It doesn't seem to be based on that. I actually have no idea what it is based on.

Look at the following behaviour (today's date is 2009-09-20):

lastRebootTime = [[NSDate date] addTimeInterval:-[self secondsSinceLastReboot]];
//last Reboot Time will contain : 2009-09-20 07:42:14 +0100

I'm absolutely certain I did not reboot my device at that time. My device hasn't been booted in a week.

Furthermore, when I unhook my device from the cable and run this app , it seems that when the device goes to sleep, the lastRebootTime starts shifting in the future. It seems mach_absolute_time doesn't keep account for sleep time. Or am i wrong about this?

I would really like to be able to get a timestamp from when the device last rebooted. Any idea's?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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));
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...