views:

71

answers:

4

I have a critical method in an Objective-C application that I need to optimize as much as possible. I first need to take some easy benchmarks on this one single method so I can compare my progress as I optimize.

What is the easiest way to track the execution time of a given method in, say, milliseconds, and print that to console.

A: 

Instruments

Chuck
I found a place where it will give me the cumulative CPU time, but the execution time of this method greatly differs per call, so I need to have a per-call breakdown, couldn't find that. A little help?
Jasconius
+1  A: 

There are quite a few ways to instrument your code, but running it through Instruments and/or Shark should give you enough information to see where your code is slow. But remember premature optimization is the root of all evil.

jshier
+2  A: 

One thing the others haven't mentioned... when you're performance-checking with Instruments or Shark, be running your app on a device rather than the simulator. The device much slower than the simulator for many things, but sometimes actually faster for some things which it's hardware accelerated for but the simulator isn't, so checking on the device is the only way to get an accurate picture.

Also, be aware that NSLogs can slow it down lots.

Mike Howard
+1 NSLog should only be used for relative measurements between code segments that contain the same number of NSLog statements.
TechZen
If I compile an application with NSLogs in it, even if I am not actively debugging, will NSLogs still execute?
Jasconius
@Jasconius - yes, they'll still be output to the terminal.
Mike Howard
+1  A: 

CFAbsoluteTimeGetCurrent() (about 6 microseconds) or mach_absolute_time() from mach/mach_time.h (somewhat faster, but you need to call mach_timebase_info() and do some conversions). You can then print to stdout or use NSLog; note that NSLog takes ages (50 ms?) so you want to do it after taking the measurements. stdout is a bit faster, I think, but doesn't go to syslog (i.e. the Xcode Organizer/iPhone Configuration Utility console).

tc.