2

I recently tried to answer a question here that was based on speed and required some way to measure how long various operations work. I see people referring to speed of different coding methods occasionally and I was wondering, What is the best way to measure speed performance in Objective-C?

Here is what I've been using:

NSDate* operation = [NSDate date];

// Code you want to measure goes here

NSLog(@"Time: %f", -[operation timeIntervalSinceNow]);

Is this an acceptable, useful measurement, and are there better alternative methods?

Community
  • 1
  • 1
Logan
  • 52,262
  • 20
  • 99
  • 128

2 Answers2

0

Sure, that works. I tend to use NSTimeInterval variables, and the

-[NSDate timeIntervalSinceReferenceDate]

method, since that gives me a scalar constant that I can do math with directly (end time interval - start time interval = elapsed time)

That's only really useful if you have a specific block of code who's performance you want to measure. The Instruments tool lets you globally monitor the amount of time your program spends in different blocks of code, which is more generally useful. It lets you find the "bottlenecks" in your code, which help you find the best candidates for optimization.

Duncan C
  • 128,072
  • 22
  • 173
  • 272
0

Stephen Canon's answer (23 upvotes) in this thread How to log a method's execution time exactly in milliseconds? is more accurate.

Community
  • 1
  • 1
Preson
  • 244
  • 2
  • 8
  • Interesting, but Stephen's answer seems to be a percentage of the whole, not the actual time it takes. Still might come in handy, thanks for pointing it out. – Logan Mar 06 '14 at 03:49
  • Why would using mach_absolute_time() be more accurate than using NSDates? They both use the same underlying clock data. NSDate just normalizes it to seconds and decimal portions of seconds. Double precision gives you plenty of resolution to do very accurate time calculations – Duncan C Mar 06 '14 at 16:22