Reason #128 • May 8th, 2026

Benchmarking with benchmark

Ruby ships with the benchmark standard gem, which provides a simple way to measure and compare the execution time of different pieces of code:

Ruby
require "benchmark"

# Single measurement
result = Benchmark.measure do
  (1..1000000).reduce(:+)
end

# User CPU time, system CPU time, total CPU time and total elapsed time
puts result
# 0.051027   0.000424   0.051451 (  0.051556)

# Comparing multiple blocks of code
Benchmark.bm do |bm|
  iterations = 10_000_000

  bm.report("for") do
    for i in 1..iterations
      a = "1"
    end
  end

  bm.report("times") do
    iterations.times { a = "1" }
  end

  bm.report("upto") do
    1.upto(iterations) { a = "1" }
  end
end
# Output:
#           user     system      total        real
# for    0.698573   0.023760   0.722333 (  0.741508)
# times  0.747916   0.010842   0.758758 (  0.832047)
# upto   0.717490   0.007442   0.724932 (  0.726068)
    

There are various options for how to present the results, refer to the benchmark documentation for more details.

History

benchmark.rb was first released as a standalone library in 2000.

It was imported into Ruby trunk in 2002 and finally shipped with Ruby 1.8.0 in 2003.

Reason #129 ?