The first rule of performance tuning is to measure your performance. If you don’t measure it, you don’t know if you’ve made any progress or if you’ve made it worse.
Here’s some very basic sample code you can use around the code you want to measure:
NSLog(@"Begin <your method name>"); NSDate *startTime = [NSDate date]; // Do something useful here NSTimeInterval elapsedTime = [startTime timeIntervalSinceNow]; NSLog(@"End <your method name>"); NSLog([NSString stringWithFormat:@"Elapsed time: %f", -elapsedTime]);
Note that NSTimeInterval is specified in seconds and it has a sub-millisecond resolution. If your code segment executes in less than a millisecond then you should run your code in a loop and measure the elapsed time across 100 or 1,000 iterations to get meaningful measurements.
Important: Make sure that you do your performance testing on the actual device and not in the simulator. Some operations are 10x slower on a device than in the simulator, while others are actually faster on the device.
The NSLog statements will show up in the Xcode Console window if you launch the app on the device from Xcode. You can also view log statements as warnings in the Organizer window in the Console tab.
October 29th, 2008 at 14:42
Hi
i also tried to mesure some thing, but in loops.
So i made exaclty the way you do, but afterwords i make:
startTime = [NSDate date];
but then i getan bad Exit error…
October 31st, 2008 at 16:28
You know, there are some great profiling tools built-in to Xcode which will do the same kind of work except without changing your code. Check out Shark and Instruments!
February 3rd, 2009 at 20:56
You should make sure that you get your elapsed time before you call the NSLog function. The NSLog function is known to add a lot of time.
# NSTimeInterval elapsedTime = [startTime timeIntervalSinceNow];
# NSLog(@”End “);
# NSLog([NSString stringWithFormat:@”Elapsed time: %f”, -elapsedTime]);
February 4th, 2009 at 08:15
@Paul: Good point. Post updated.
July 29th, 2011 at 19:24
NSLog([NSString stringWithFormat:@”Elapsed time: %f”, -elapsedTime]);
should be written as
NSLog(@”Elapsed time: %f”, -elapsedTime);