Wednesday, May 22, 2013

Profiling in Rails with Ruby's Profiler

This is a nifty trick:

rails c 2>&1 | tee profile.txt

Then use Ruby's Profiler:

require 'profile'
SomeClass.some_method
exit (or ctrl-d)

Then filter the output by your classname:

grep -E "SomeClass\#|cumulative   self|seconds    call" profile.txt
Which results in:

  %   cumulative   self              self     total
 time   seconds   seconds    calls  ms/call  ms/call  name
  1.05     0.79      0.01        5     2.00     2.00  SomeClass#_validate_callbacks
  0.00     0.95      0.00       13     0.00     0.00  SomeClass#_create_callbacks
  0.00     0.95      0.00       13     0.00     0.00  SomeClass#_update_callbacks
  0.00     0.95      0.00       15     0.00     0.00  SomeClass#reflections
  0.00     0.95      0.00       12     0.00     0.00  SomeClass#_save_callbacks
  ...

Update: It's not Profiler, but be sure to also read Matt Aimonetti's post, Inspecting Rails 4 Using Ruby 2.0, which has some great tips on using Rack middleware and TracePoint. Also, check out ruby-prof.

No comments: