Matt Rajca

Jul 01 2011

Quick and Dirty Profiling with Blocks

Instruments is an amazing tool for finding all sorts of performance issues in your applications, 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. Each time you want to profile a chunk of code, you need to wrap it in nearly 8 lines of boilerplate code.

By writing a profile function that takes a block of work as an argument, this problem becomes trivial.

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);
}

To profile some code, all we now have to do is call profile and pass our worker block; the timing will get logged to standard out.

profile("Long Task", ^{ performLongTask() } );

19 notes

  1. cheap-papers reblogged this from mattrajca
  2. mattrajca posted this
Page 1 of 1