Ruby Timing Shortcut

June 10th, 2008 By: Daniel

Recently I was trying to optimize my code a little and needed a quick way to compare the speed of different code snippets. Of course Rails comes with the Benchmark module for doing just that. It is, however, in my opinion a bit clunky for quick tests. Look at all the typing it takes just to find the average speed of a snippet over 100 iterations:

Benchmark.bm do |x|
  x.report do
    100.times do
      (1...1000).to_a.sum
    end
  end
end

So I tossed this into my ~/.irbrc file:

class Integer
  def ti(&block)
    Benchmark.bm do |x|
      x.report do
        self.times do
          yield
        end
      end
    end
  end
end

And now I can “time it” like this:

>> 100.ti {(1...1000).to_a.sum}
      user     system      total        real
  0.540000   0.050000   0.590000 (  0.597664)
=> true

Much nicer!

Leave a Reply