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] );
Here's my answer for clock timers using both
mach_absolute_time()
, based on compute method shown here, andNSDate
. The are actually the same in terms of accuracy.Mach version
NSTimeInterval version
Results:
Note the resolution on both of these is really good.
*If you look at the edit history of this post, you can see the danger of using
float
in the place of adouble
!A better option is
CACurrentMediaTime()
which usesmach_absolute_time()
but converts it to aCFTimeInterval
(i.e., time in seconds as a double) for you.Use
NSTimeInterval startTime = [NSDate timeIntervalSinceReferenceDate]
to get a start time, and thenNSLog (@"Operation took %f seconds.", [NSDate timeIntervalSinceReferenceDate] - startTime);
at the end.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.)