Tracing and profiling Ruby code

Every child knows that premature optimization is the root of all evil, and even when optimization is necessary, we should concentrate on the bottlenecks. This is where profiling becomes crucial. Ruby includes a simple profiler in the standard library, so to generate a report of program execution you just have to invoke it with ruby -r profile or add require "profile" to the code. In fact the whole profiler is implemented in only 59 lines of Ruby and relies on set_trace_func method to register a callback tracing certain events during program execution (method calls and returns in this case). This tool should suffice for simple profiling, but if you need something faster and more powerful you should rather try ruby-prof.

The powerful introspection features of dynamic languages make tricks like this not only possible, but also straightforward. This gives me an idea that the same approach could be used to implement an aspect-oriented library for Ruby — but I’m almost sure somebody has already tried this.

Post a Comment

Your email is never published nor shared. Required fields are marked *