Timing things in Objective-C: A stopwatch
This one is very geeky, but also very useful to those of you out there who need it.
There are a lot of times that a developer needs to see just how efficient a piece of code is. Or, to be more accurate, determine what part of their system is causing all the ugly slow-down — at least, that’s where I usually find myself. This can be as tricky as you want it to be, really. So I decided to put together a simple utility that I can use whenever the need strikes me.
Usually, timing takes variables to be shared between functions, or worse, objects. Then there’s figuring out (every time) how to do it right. Well, look no further for MMStopwatch will solve all of your ills.
My goal was to make this as simple to use as possible so that I’d be more likely to use it — and thus find efficiencies. There are tons of bells and whistles that could be added to something like this, but my point was more basic — intentionally.
How you use it:
[MMStopwatchARC start:@"My Timer"];
// your work here ...
[MMStopwatchARC stop:@"My Timer"];
What it outputs (in the log):
MyApp[4090:15203] -> Stopwatch: [My Timer] runtime: [0.029]
Download it and play to your heart’s content. You can use this in any way without any attribution.
Some geekier notes:
Okay, for those of you that want just a touch more details on this… There are 2 versions of the MMStopwatch class (one for traditional objective-c projects and one for the newer ARC-based projects). I find myself having to write a fair amount of my “library” code twice so that it works in both types of projects. So I’ve packaged both up here. You’ll be able to tell the difference.
There is also a print: method where you can get any timer (by name) to print out it’s current time value without stopping the timer. Helpful when you want to time the inside of a loop
Also, this is built in a way so that you don’t need to create an object to do the work. That keeps the work to 1-line and makes it far more likely that I will use it.