High-resolution timer for iPhone?

zpasternack picture zpasternack · Aug 22, 2010 · Viewed 7.2k times · Source

I'm looking for high-resolution timing code for iPhone, in order to do some performance timings. I'd like to write code like this:

HighResolutionTimer* myTimer = [[HighResolutionTimer alloc]init];
[myTimer start];
[self doSomeLengthyOperation];
NSLog( @"doSomeLengthyOperation took %f seconds", [myTimer elapsedTime] );

Answer

hotpaw2 picture hotpaw2 · Aug 22, 2010

Look into mach_absolute_time() in the mach/mach_time.h header.

Don't use NSDate. NSDate isn't even guaranteed to not go backwards occasionally, when ntp does its thing.

(Devices can have clock drift. If the iOS device drifts fast a few seconds, then when NTP corrects this drift, you will see the clock suddenly go backwards a few seconds. Very bad for timing use. mach_time uses a counter that doesn't ever get corrected by NTP, thus can't go backwards, thus is far better for timing.)