Ruby Benchmarking

Tips Link to heading

Disable garbage collection when benchmarking for more accurate results.

GC.disable

# ------------------------------------------------------------------------------
# Code goes here

# ------------------------------------------------------------------------------

GC.enable

Basic Link to heading

require 'benchmark'

count  = 10_000
io     = StringIO.new
result = Benchmark.measure do
  count.times do
    io.puts 'Hello'
  end
end

puts result

#     user     system       toal        real
# 0.045354   0.099388   0.144742 (  0.145264)

Advanced Link to heading

require 'benchmark'
require 'stringio'
require 'pp'

count  = 10_000
io     = StringIO.new
result = Benchmark.bmbm do |benchmark|
  benchmark.report('inspect') do
    count.times do
      io.puts 'Hello'.inspect
    end
  end

  benchmark.report('pretty_inspect') do
    count.times do
      io.puts 'Hello'.pretty_inspect
    end
  end
end

# Rehearsal --------------------------------------------------
# inspect          0.007339   0.000000   0.007339 (  0.007391)
# pretty_inspect   0.625188   0.330933   0.956121 (  0.982394)
# ----------------------------------------- total: 0.963460sec
#
#                      user     system      total        real
# inspect          0.007655   0.000510   0.008165 (  0.008544)
# pretty_inspect   0.668881   0.257305   0.926186 (  0.948372)

Legendary Link to heading

Use these gems for more advanced benchmarking strategies: