Wednesday, August 21, 2013 [Tweets] [Favorites]

NanoProfiler

Tomer Shiri’s NanoProfiler let’s you “measure a function’s runtime without adding a single line of code to the original function” (via ManiacDev). It’s implemented using TheWrapper, his library that uses the Objective-C runtime to add pre-run and post-run blocks to a method. I like the idea, though his method of calling the original IMP does not seem correct for methods with different types of arguments and return values. At the moment, I can’t think of a fully reliable way to do that, though.

5 Comments

Isn't it already possible to do such thing using DTrace ?

@Jean-Daniel Yes for the profiling, but I was interested in the general idea of adding Objective-C code that runs before or after a method.

At some point in the distant past, I had looked into AspectCocoa (http://cocoadev.com/AspectCocoa) and the conclusion with the runtime back then was that it was really hard to cover all the method signatures, but possible if you hard-code common signatures, and then fall back on much slower mechanisms like forwardInvocation for other cases. The basic idea of TheWrapper is the same, but only uses one single function to replace the IMP, and indeed I am not sure the behavior is correct for all signatures (it seems it would depend on the compiler as well, and the architecture??).

@charles It’s pretty messy to use -forwardInvocation: for this, and it looks like AspectCocoa even has to generate and compile code for methods that NSInvocation can’t handle.

@michael Indeed my point was that it seems really hard to swizzle methods in a very general way, and it is not surprising that you "can’t think of a fully reliable way to do that" given for instance what AspectCocoa ended up doing after really thinking hard about it :-)

Stay up-to-date by subscribing to the Comments RSS Feed for this post.

Leave a Comment