15

I'm trying to figure out what the best way to profile a Sinatra app is. I'd like a solution that would give me a time profile of all methods within a path, including the rendering of the haml.

Has anyone profiled a Sinatra app? Any pointers?

Ecton
  • 10,702
  • 2
  • 35
  • 44
  • I typically perform manual instrumentation of all methods within a route. This isn't a great answer, though, so I'll just leave it as a comment. I wonder if the built-in 'profile' library has a mechanism to report the snapshot early. – Phrogz Dec 05 '10 at 16:16

2 Answers2

9

Here's a technique that works, not sure if it's the best.

require 'sinatra'
require 'profiler'

get '/' do
  Profiler__.start_profile
  do_it_fast
  do_it_slow
  do_it_fast
  Profiler__.stop_profile
  Profiler__.print_profile(STDOUT)
  "done"
end

def do_it_fast
  1.upto(100){ Math.sqrt(rand) }
end

def do_it_slow
  1.upto(100_000){ (Math.sqrt(rand)).ceil }
end

#=> In the console:
#=>  %   cumulative   self              self     total
#=> time   seconds   seconds    calls  ms/call  ms/call  name
#=> 68.45     2.82      2.82        3   940.00  1373.33  Integer#upto
#=> 11.41     3.29      0.47   100200     0.00     0.00  Kernel.rand
#=> 10.92     3.74      0.45   100000     0.00     0.00  Float#ceil
#=>  9.22     4.12      0.38   100200     0.00     0.00  Math.sqrt
#=>  0.00     4.12      0.00        2     0.00     5.00  Object#do_it_fast
#=>  0.00     4.12      0.00        1     0.00  4110.00  Object#do_it_slow
#=>  0.00     4.12      0.00        1     0.00  4120.00  #toplevel
Phrogz
  • 296,393
  • 112
  • 651
  • 745
6

IMO, in this case the best tool is perftools.rb, which is based on Google Perftools. It can even produce such graphs (awesome!): http://perftools-rb.rubyforge.org/examples/sinatra.gif

As a regular user of perftools.rb, I can say that it greatly helps to find bottlenecks in your app and compare different strategies.

Search for "perftools.rb" at github.com

Daniel Vartanov
  • 3,243
  • 1
  • 19
  • 26