a simple wrapper for Benchmark.bm

require 'benchmark'

def compare(times = 1, label_width = 12)
  Benchmark.bm(label_width) do |x|
    yield Benchmark::ReportProxy.new(x, times)
  end
end

class Benchmark::ReportProxy
  def initialize(bm, iterations)
    @bm = bm
    @iterations = iterations
  end

  def method_missing(method, *args, &block)
    args.unshift(method.to_s + ':')
    @bm.report(*args) do
      @iterations.times { block.call }
    end
  end
end

usage

compare 100_000 do |try|
  first, last = %w(Mislav Marohnic)

  try.join          { [first, last].join(' ') }
  try.interpolation { "#{first} #{last}"      }
  try.concatenation { first + ' ' + last      }
end

output

                  user     system      total        real
join:           0.520000   0.070000   0.590000 (  0.693261)
interpolation:  0.490000   0.060000   0.550000 (  0.631762)
concatenation:  0.540000   0.060000   0.600000 (  0.678998)