Search

A Timing Utility

Mark Dalrymple

2 min read

Mar 7, 2012

A Timing Utility

Sundial with apple, found by the Loudoun Museum in Leesburg, VA Timing how long a block of code takes is a useful tool. Maybe you’re choosing between two different calls that do similar things and you’re wondering which one is faster. If one is faster, is it faster-enough to make any difference? The usual techniques involve using a profiler like Instruments, or calling a time function like gettimeofday() before and after your code and calculating the delta. Those of us on mach-based systems like iOS and OS X can use mach_absolute_time(), which is the finest-grained timepiece available on the system.

mach_absolute_time() returns a count. But you don’t know what units that count is in. How do you figure out the units? mach_timebase_info() will fill in a structure with the values you can use to scale mach_absolute_time()’s counter, yielding nanoseconds – billionths of a second. If you want seconds, you can divide nanoseconds by the constant NSEC_PER_SEC (one billion). NSEC_PER_SEC is easier to read than making sure that a division by 100000000 has enough zeroes in it.

That’s all well and good, but kind of tedious. Wouldn’t it be great if you could say “yo, time this block for me”, then you put your interesting code in the block. Here is a little utility, based on some code from a couple of years ago that does just that.

So how do you use it? Say you were timing to see which takes longer, isEqual: or isEqualToString:. Put a loop that makes the call inside of a block, and time it:

Running gives you some timings:

% <b>./compare-time</b>
isEqual: time: 0.635283
isEqualToString: time: 0.593058

As you’ll see in a later post, you can start making informed decisions from this test, and from other tests.

Edit: Advanced iOS Instructor Jonathan Blocksom has put the code into a gist: https://gist.github.com/2006587.

_Have a passion for profiling and performance? Our Advanced Mac OS X and Advanced iOS Bootcamps feature sections on performance tuning and Apple’s Instruments performance tools. _

Mark Dalrymple

Author Big Nerd Ranch

MarkD is a long-time Unix and Mac developer, having worked at AOL, Google, and several start-ups over the years.  He’s the author of Advanced Mac OS X Programming: The Big Nerd Ranch Guide, over 100 blog posts for Big Nerd Ranch, and an occasional speaker at conferences. Believing in the power of community, he’s a co-founder of CocoaHeads, an international Mac and iPhone meetup, and runs the Pittsburgh PA chapter. In his spare time, he plays orchestral and swing band music.

Speak with a Nerd

Schedule a call today! Our team of Nerds are ready to help

Let's Talk

Related Posts

We are ready to discuss your needs.

Not applicable? Click here to schedule a call.

Stay in Touch WITH Big Nerd Ranch News