Request Profiler

request_profiler is a rack middleware that allows you to profile rack requests using ruby-prof. It sits out of the way until it’s triggered using a specific request parameter. Once triggered, it will profile the request and dump a log file.

Setup

After the gem is installed, it’s used in the same way any rack middleware is set up. In Rails, you’d probably want to do something like this:

config.middleware.use "Rack::RequestProfiler"

request_profiler takes a few optional parameters:

:printer

the ruby-prof printer to use. Defaults to RubyProf::GraphPrinter.

:exclude

a list of regexes (like [/Integer#times]) that will not appear in the profile log. This is most commonly used for methods that take a block, where you don’t care how much time was spent in the method itself.

:path

the path to write the log files to. If request_profiler is running under Rails, this defaults to Rails.root/tmp/performance, otherwise it defaults to $TMPDIR/performance.

Using request_profiler

When you get to the point where you’d like to profile a request, you just add profile_request=true to the end of your request’s query string. By default, this will use the RubyProf::PROCESS_TIME profiler. If you’d like to use a different profiler, you can specify the profiler class instead of true in the query string. For example,

profile_request=memory

will use the RubyProf::MEMORY profiler. Note that the profilers other than PROCESS_TIME and WALL_TIME require a patched ruby interpreter, as mentioned in the ruby-prof documentation. REE should work out of the box, but as far as I know, these patches don’t yet exist for ruby 1.9.

Bugs Under Ruby 1.9.2

ruby_prof uses a ruby method called set_trace_func, which tends to crash under ruby 1.9.2. I have an experimental patch which backports the fix in the 1.9.3 branch to 1.9.2, and adjusts the stack depth threshhold ruby uses, which fixes some other interpreter crashes I was seeing. If you run into similar issues, you should grab the patch located under patches/set_trace_func_fix192.patch. With rvm, it’s as simple as

rvm install 1.9.2p0 --patch /path/to/set_trace_func_fix192.patch