this code tastes like coffee!

and other observations 
« Back to blog

How to use NSTimeInterval to optimize your code

Want to see how long a particular block of code is taking to execute? Use NSTimeInterval:

NSDate *method1Start = [NSDate date];
//code we want to time
NSLog(@"Method1 time: %f",[[NSDate date] timeIntervalSinceDate:method1Start]);

If you are timing within a loop, you can add the time interval to a running total:

NSDate *method1Start;
NSTimeInterval method1Total = 0;

while(loop you are working in) {
     //some code

    method1Start = [NSDate date];
     //code we want to time
     method1Total = method1Total + [[NSDate date] timeIntervalSinceDate:method1Start];

     //other code
}

NSLog(@"Method1 time: %f", method1Total);

Comments (1)

May 09, 2011
Chris Ladd said...
Another way you can do this, without the overhead of creating an NSDate object is CFAbsoluteTimeGetCurrent(), which also returns an NSTimeInterval. Call it twice, subtract one from the other, and you're good to go.

Leave a comment...