Saturday, February 17, 2007

Timing operations

I'll sometimes want to measure the time a certain operation takes and compare it with another operation or to compare it with another implementation of the same operation. Here's the fragment of Cocoa code I use to do that:

NSDate *startTime = [NSDate date];

{ ... } // the operation that I'm timing

NSTimeInterval elapsedTime = -[startTime timeIntervalSinceNow];

NSLog(@"That took %f seconds", elapsedTime);

This code grabs the current time using NSDate, does something, calculates the time spent doing the operation, and then logs the result.

Wednesday, February 14, 2007

Optional breakpoints

I sometimes find myself wanting to break into the debugger only after a series of steps that would otherwise trigger the breakpoint. I find the following code snippet useful in some of these situations.

BOOL optionKeyIsDown = (([[NSApp currentEvent] modifierFlags] & NSAlternateKeyMask) != 0);
if (optionKeyIsDown) {
NSLog(@"voila");
}

You set a breakpoint on the NSLog() which it's only triggered when you have the option key down.

It's easy to use another modifier key if you like by using another key mask constant instead of NSAlternateKeyMask.

The downside of course is that it requires a little piece of live code that needs to be cleaned up before ship time.

This same approach can useful for other things as well. For example, you could trigger a data structure verification routine. Maybe that routine is very time consuming and you don't want it interfering with normal execution, but by simply holding down the option key (or may multiple modifier keys) you can trigger some special code.

Sunday, February 11, 2007

A simple ~/.gdbinit file

I have a one line .gdbinit file containing:

 fb -[NSException raise] 

This is executed each time gdb (the Xcode debugger) is started. With this the code will break into the debugger whenever an exception is raised by a Cocoa program.

fb is "forward break" which unlike plain b, or "break", will set a breakpoint on code that hasn't been loaded yet.

About My Mac