Oct 07

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.

 

written by Nick \\ tags: , ,

5 Responses to “The First Rule of Performance Tuning”

  1. Nam Says:

    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…

  2. Corwin Says:

    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!

  3. Paul S Says:

    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]);

  4. Nick Says:

    @Paul: Good point. Post updated.

  5. bob Says:

    NSLog([NSString stringWithFormat:@”Elapsed time: %f”, -elapsedTime]);
    should be written as
    NSLog(@”Elapsed time: %f”, -elapsedTime);

Leave a Reply