As the time nears for one of my applications to move towards general release, performance is the concern of the day. There are still bugs to fix, visual indiscretions to … discrete, etc. My good man Becker got some profiling code into the application, but I found the results difficult to read through. Last week I attended Ruby East and caught a nice presentation by Ezra Zygmuntowicz of Engine Yard regarding Ruby performance and optimization. During the presentation, he showed a bit of code he includes in his applications to make wrapping select blocks of code for profiling easier. He was nice enough to share his code with me, and allow me to present it here for all of you.

Where does the code go?
Well, you can put it anywhere really. For my quick and dirty testing I put it at the bottom of RAILS_APP/config/environment.rb, but you could just as easily put it in it’s own file in your RAILS_APP/lib directory, or any number of other options.

  1. module Kernel
  2.     def __profile__(name, min=1)
  3.         require 'ruby-prof' unless defined?(RubyProf)
  4.         return_result = ''
  5.         result = RubyProf.profile do
  6.             100.times{return_result = yield}
  7.         end
  8.         printer = RubyProf::GraphHtmlPrinter.new(result)
  9.         path = File.join(RAILS_ROOT, 'log', "#{name}.html")
  10.         File.open(path, 'w') do |file|
  11.             printer.print(file, {:min_percent => min, :print_file => true})
  12.         end
  13.         return_result
  14.     end
  15. end

OK, now how do I use it?
All you have to do to use the profiler is wrap whatever block of code you want to profile in __profile__

  1. def my_action
  2.     # code before
  3.     __profile__("monkey_profile") do
  4.         @bobo = Monkey.find(:first, :conditions => ["likes_bananas = ?",params[:does_bobo_like_bananas])
  5.     end
  6.     #code after
  7. end

Now what do I do?
An HTML file will be created in RAILS_APP/log/something.html. Where something is the string that you passed to the __profile__ call when you wrapped it around your code. In my example the file would have been called “monkey_profile.html”. Pop it open in your favorite browser and take a look.

This is confusing, what do all these numbers mean?
I don’t know. Really, I don’t. I am rather new to profiling, so I can’t really explain the generated report with any accuracy. Take a look at the ruby-prof docs, or find someone who knows about profilers in general and ask them to explain it to you. If you are a profiling genius, or you know of any good online resources for getting useful information out of ruby-prof reports, please let me know.

Happy profiling.