iOS Dev Nugget 46 Timing Small Bits of Code


Need to run a code review on your codebase? Hire me

Xcode has excellent instrumentation tools for profiling your code. But sometimes you want to compare the performance of 2 versions of the same code performing the same task. Here's a bit of code I use to print out how long it takes to run a block of code:

void moTime1(void(^block)(void), NSString* s) {
    NSDate* start = [NSDate date];
    NSLog(@"%@ %f", s, [[NSDate date] timeIntervalSinceDate:start]);

Here's how you use it to compare the performance of 2 pieces of code:

}, @"version 1");

}, @"version 2");

And it should print something like:

> version 1 0.100000
> version 2 0.001000

While not terribly accurate, you can see at a glance that version 2 is 2 orders of magnitude faster.

Your feedback is valuable: Do you want more nuggets like this?   Yes   or   No


Like this and want such iOS dev nuggets to be emailed to you, weekly?

Sign Me Up! or follow @iosdevnuggets on Twitter


View archives of past issues