Profile a rails controller action

I picked up this technique a while back and have found it quite handy.

When it’s in place, you can add ?profile=true to any URL that hits a controller. Your action will run as usual, but instead of delivering the rendered page to the browser, it’ll send a detailed, nicely formatted ruby-prof page that shows where your action spent its time.

First, add ruby-prof to your Gemfile, probably in the development group:

group :development do
    gem "ruby-prof"
end

Then add an around filter to your ApplicationController:

around_action :performance_profile if Rails.env == 'development'

def performance_profile
  if params[:profile] && result = RubyProf.profile { yield }

    out = StringIO.new
    RubyProf::GraphHtmlPrinter.new(result).print out, :min_percent => 0
    self.response_body = out.string

  else
    yield
  end
end

Reading the ruby-prof output is a bit of an art, but I’ll leave that as an exercise.

Additional note by ScottJShea:
If you want to change the measurement type place this:

RubyProf.measure_mode = RubyProf::GC_TIME #example

Before the if in the profile method of the application controller. You can find a list of the available measurements at the ruby-prof page. As of this writing the memory and allocations data streams seem to be corrupted (see defect).

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)