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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With