Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Profile a rails controller action

What is the best way to profile a controller action in Ruby on Rails. Currently I am using the brute-force method of throwing in puts Time.now calls between what I think will be a bottleneck. But that feels really, really dirty. There has got to be a better way.

like image 349
salt.racer Avatar asked Aug 27 '08 23:08

salt.racer


1 Answers

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).

like image 71
Rob Davis Avatar answered Sep 23 '22 15:09

Rob Davis