Profiler

In most cases, you can improve the performance of a slow program by removing the bottleneck. The profiler is a tool that finds the bottleneck. In order to add profiling to your Ruby program, you need to first load the Profile library using the command-line option -r profile. Here is the sample output from profiled execution. You can tell Object#fact method is a bottleneck.

% ruby -r profile sample/fact.rb 100
9332621544394415268169923885626670049071596826438162146859296389521759999
3229915608941463976156518286253697920827223758251185210916864000000000000
000000000000
  %   cumulative   self              self     total
 time   seconds   seconds    calls  ms/call  ms/call  name
 66.67     0.07      0.07        1    66.67    66.67  Object#fact
 16.67     0.08      0.02        1    16.67    16.67  Bignum#to_s
  0.00     0.08      0.00        5     0.00     0.00  Fixnum#*
  0.00     0.08      0.00        2     0.00     8.33  IO#write
  0.00     0.08      0.00        1     0.00     0.00  Fixnum#==
  0.00     0.08      0.00       95     0.00     0.00  Bignum#*
  0.00     0.08      0.00        1     0.00     0.00  Module#method_added
  0.00     0.08      0.00      101     0.00     0.00  Fixnum#>
  0.00     0.08      0.00        1     0.00    16.67  Kernel.print
  0.00     0.08      0.00        1     0.00     0.00  String#to_i
  0.00     0.08      0.00        1     0.00     0.00  Array#[]
  0.00     0.08      0.00      100     0.00     0.00  Fixnum#-
  0.00     0.08      0.00        1     0.00   100.00  #toplevel

Get Ruby in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.