iPhone Profiling using NSLog and Xcode Console
April 5, 2009 § Leave a comment
This is an interesting and cool approach to calculate time elapsed using NSDate. It requires only 3 lines of code. It is ideal for Profiling and benchmark performance using NSLog. Or you can alter the code and use it as features for the app.
NSDate *then = [NSDate date]; // Create a current date
// enter code
NSDate *now = [ NSDate date];
NSLog(@”Time elapsed: %f”, [now timeIntervalSinceDate:then]);
NSDate *startTime = [NSDate date];
// Insert codes here
NSTimeInterval elapsedTime = [startTime timeIntervalSinceNow];
NSLog([NSString stringWithFormat:@”Elapsed time: %f”, -elapsedTime]);
Since startTime is earlier than timeIntervalSinceNow, we convert negative value of startTime to negative value of elapsedTime, resulting to positive time in sec with data type of float. Convert float to a string with stringWithFormat: method and print to NSLog.
NSTimeInterval is specified in seconds and it has a sub-millisecond resolution.