Profiling Ruby with ruby-prof

Posted About 11 years ago. Visible to the public.

require 'ruby-prof' # you don't need this if you have ruby-prof in your Gemfile

You can set one of the things you want to measure by using (default is PROCESS_TIME most useful ones are PROCESS_TIME, MEMORY, CPU_TIME):
RubyProf.measure_mode = RubyProf::PROCESS_TIME
RubyProf.measure_mode = RubyProf::WALL_TIME
RubyProf.measure_mode = RubyProf::CPU_TIME
RubyProf.measure_mode = RubyProf::ALLOCATIONS
RubyProf.measure_mode = RubyProf::MEMORY
RubyProf.measure_mode = RubyProf::GC_RUNS
RubyProf.measure_mode = RubyProf::GC_TIME

then kick off the profiler by

result = RubyProf.profile do
  # whatever code / method you want to profile here
end

To simply print stuff in your console and be overwhelmed (especially if you have activerecord/railsy objects)

printer = RubyProf::FlatPrinter.new(result)
printer.print(STDOUT)

Other useful printers available are:

RubyProf::FlatPrinter
RubyProf::FlatPrinterWithLineNumbers
RubyProf::GraphPrinter
RubyProf::GraphHtmlPrinter
RubyProf::CallTreePrinter
RubyProf::CallStackPrinter
RubyProf::MultiPrinter

I find GraphHtmlPrinter useful, use it as:

printer = RubyProf::GraphHtmlPrinter.new(result)
# to save results to tmp/profile_data.html
File.open("tmp/profile_data.html", 'w') { |file| printer.print(file) }

open the file 'tmp/profile_data.html'

To dig deeper please RTFM

Nasir Jamal
Last edit
About 11 years ago
Posted by Nasir Jamal to HouseTrip Deck (2013-01-14 14:19)