Instruments is an amazing tool for finding all sorts of performance issues in software, but sometimes, all you want to do is log a quick and dirty timing of a snippet of code.
Mark Darlymple once posted a quickie that does just this. Unfortunately, the code isn’t very reusable. You have to wrap each chunk of code you want to profile with nearly 8 lines of boilerplate code.
We can reduce some of this complexity by writing a profile
function that takes a block of work as an argument instead.
void profile (const char *name, void (^work) (void)) {
struct timeval start, end;
gettimeofday (&start, NULL);
work();
gettimeofday (&end, NULL);
double fstart = (start.tv_sec * 1000000.0 + start.tv_usec) / 1000000.0;
double fend = (end.tv_sec * 1000000.0 + end.tv_usec) / 1000000.0;
printf("%s took %f seconds", name, fend - fstart);
}
Now, all we have to do is call profile
and pass in the block we wish to time; the timing will get logged to standard out.
profile("Long Task", ^{ performLongTask(); } );