(((1 << 3) & (~0xF | (3 >> 1) & (~0xFFED << 4))) | ~(7 + 0xDEADBEEF << 7) >> 5) >> 5 ^ (0xDE ^ (~0xF32 >> (5 | 74 >> 2)))

mach_absolute_time on the iPhone

Devin Lane | Programming | Wednesday, October 1st, 2008

As programmers on OS X are well aware, the units of mach_absolute_time() have been nanoseconds since 10.2, although this was only documented since 10.5. As the iPhone runs a slimmed down version of OS X, I thought it reasonable that the units would remain the same on the device.

Not so.

On the iPhone, the timebase is different. The mach_timebase_info structure contains a numerator and denominator that can be used to convert between the result returned by mach_absolute_time() and nanoseconds. On OS X Leopard, the numerator and denominator are both 1, meaning that the units are already in nanoseconds. On OS X iPhone, the numerator is 1,000,000,000, while the denominator is 6,000,000. Thus, every unit of absolute time on the iPhone is 166.67 nanoseconds.

So if you’re trying to get some timing from the iPhone using mach_absolute_time() and seeing times that indicate faster results on the iPhone, (not that this happened to me…), make sure to account for the difference in timebase.

Here’s the code for conversion between the iPhone’s mach_absolute_time() and nanoseconds:

/* Get the timebase info */
mach_timebase_info_data_t info;
mach_timebase_info(&info);

uint64_t start = mach_absolute_time();

/* Do some code */

uint64_t duration = mach_absolute_time() - start;

/* Convert to nanoseconds */
duration *= info.numer;
duration /= info.denom;

/* Log the time */
NSLog(@"My amazing code took %lld nanoseconds!", duration);

Powered by WordPress | Theme by Roy Tanck, modifications by Devin