views:

1004

answers:

3

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.

+4  A: 

Use the Benchmark standard library and the various tests available in Rails (unit, functional, integration). Here's an example:

def test_do_something
  elapsed_time = Benchmark.realtime do
    100.downto(1) do |index|
      # do something here
    end
  end
  assert elapsed_time < SOME_LIMIT
end

So here we just do something 100 times, time it via the Benchmark library, and ensure that it took less than SOME_LIMIT amount of time.

You also may find these links useful: The Benchmark.realtime reference and the Test::Unit reference. Also, if you're into the 'book reading' thing, I picked up the idea for the example from Agile Web Development with Rails, which talks all about the different testing types and a little on performance testing.

Chris Bunch
This answer tells you how to make sure your action is running quickly enough. It doesn't help you with profiling, which is finding out which part of the action is taking the most time.
Jon Bright
+5  A: 

There's a Railscast on profiling that's well worth watching

http://railscasts.com/episodes/98-request-profiling

Stuart
+1  A: 

You might want to give the FiveRuns TuneUp service a try, as it's really rather impressive. Disclaimer: I'm not associated with FiveRuns in any way, I've just tried this service out.

TuneUp is a free service whereby you download a plugin and when you run your application it injects a panel at the top of the screen that can be expanded to display detailed performance metrics.

It gives you some nice graphs, including one that shows what proportion of time is spent in the Model, View and Controller. You can even drill right down to see the individual SQL queries that ActiveRecord is executing if you need to and it can show you the underlying database schema with another click.

Finally, you can optionally upload your profiling data to the FiveRuns site for community performance analysis and advice.

John Topley