A Timing Utility
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,
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.