Ruby Benchmark

If you just want to see how fast a bit of code is you can use the Benchmark module which is part of the Ruby Standard Library.

require 'benchmark'

puts Benchmark.measure { (0..9999999).each{|n| n * 99999999} }

# user system total real

# 0.770000 0.010000 0.780000 ( 0.773784)

If you want to compare two or more bits of Ruby code that do the same thing and see how fast they are against each other then you can use the ‘bm’ method on Benchmark.

require 'benchmark'

Benchmark.bm do |z|
  z.report { x = 0; (0..9999999).each{|n| x += n * 99999999} }
  z.report { x = (0..9999999).map{|n| n * 99999999}.sum }
  z.report { x = 0; for n in 0..9999999; x += n * 99999999; end }
end


Posted

in

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *