Ruby - Benchmarking and Profiling

Introduction

Ruby's standard library includes a module called Benchmark.

Benchmark provides several methods that measure the speed it takes to complete the code you provide. For example:

Demo

require 'benchmark' 
puts Benchmark.measure { 10000.times { print "." } }

Result

This code measures how long it takes to print 10,000 periods to the screen.

Because measure accepts code blocks, you can make it as elaborate as you wish:

Demo

require 'benchmark' 
iterations = 1000000 #  w w  w  .j  av a  2  s.  c  o  m

b = Benchmark.measure do 
  for i in 1..iterations do 
    x = i 
  end 
end 


c = Benchmark.measure do 
  iterations.times do |i| 
    x = i 
  end 
end 

puts b 
puts c

Result

Here, you benchmark two different ways of counting from one to one million.

Related Topics