Profile Ruby with Blocks

Ruby makes it easy to profile any chunk of code, using Blocks and Procs. All you have to do is wrap the code you want to profile in a block and and ruby’s magic takes care of the rest.

def profile block_description, &block
  start_time = Time.new
  block.call
  duration = Time.new - start_time
  puts "#{block_description}: #{duration} seconds"
end

profile '25000 doublings' do
  number = 1
  25000.times do
    number = number + number
  end
  puts "#{number.to_s.length} digits"
end

profile 'count to a million' do
  number = 0
  1000000.times do
    number = number + 1
  end
end