Simple Profiling of a Ruby Application

September 18, 2014

A few days back I wrote about benchmarking your Ruby code, today I want to show you quickly how to profile your code. We have all been there, slow code, select n+1 and all the other craziness that goes on when you write code. You end up putting in code to time blocks of code, or you buy a third-party profiler to tell you where you code is crap.

Ruby has a built-in crap-o-meter, and it is part of the Standard Library so you can use it for free!

As you can see in the code, one little require bringing in the ‘profile’ library, and that is it. Running this code outputs:

10715086071862673209484250490600018105614048117055336074437503883703510511249361224931983788156958581275946729175531468251871452856923140435984577574698574803934567774824230985421074605062371141877954182153046474983581941267398767559165543946077062914571196477686542167660429831652624386837205668068375
  %   cumulative   self              self     total
 time   seconds   seconds    calls  ms/call  ms/call  name
 50.00     0.02      0.02     1874     0.01     0.01  Bignum#+
 50.00     0.04      0.02      999     0.02     0.04  nil#
  0.00     0.04      0.00        1     0.00    40.00  Range#each
  0.00     0.04      0.00        1     0.00     0.00  TracePoint#enable
  0.00     0.04      0.00        1     0.00     0.00  Module#method_added
  0.00     0.04      0.00      999     0.00     0.01  Object#add
  0.00     0.04      0.00        1     0.00     0.00  Bignum#to_s
  0.00     0.04      0.00        2     0.00     0.00  IO#write
  0.00     0.04      0.00        1     0.00     0.00  IO#puts
  0.00     0.04      0.00        1     0.00     0.00  Kernel#puts
  0.00     0.04      0.00        1     0.00     0.00  TracePoint#disable
  0.00     0.04      0.00        1     0.00    40.00  #toplevel

Pretty interesting stuff right? All I needed was a require and I get some awesome profiling. You would obviously want to hide this behind a flag of some sorts. Nonetheless awesomeness!


Discussion, links, and tweets

My name is Deon Heyns and I am a developer learning things and documenting them in realtime. Python, Ruby, Scala, .NET, and Groovy are all languages I have written code in. I appeared in the New York Post once. I host my code up at GitHub and Bitbucket so have a look at my code, fork it and send those pull requests.

comments powered by Disqus