Benchmarks

suggest change

Benchmarking allows you to measure and compare the execution time and memory footprint of different implementations. Ruby offers built-in tools through the standard Benchmark module as well as popular gems like benchmark-ips for rigorous statistical performance measurements.


1. The Standard Benchmark Module

Ruby ships the Benchmark module with every installation (since Ruby 4.0 as a bundled gem, so add gem 'benchmark' to your Gemfile when using Bundler). To use it, simply require benchmark:

require 'benchmark'

Measuring a Single Block with Benchmark.measure

The simplest way to measure execution time is Benchmark.measure:

require 'benchmark'

time = Benchmark.measure do
  (1..1_000_000).map { |n| n * 2 }
end

puts time
# Output format (user, system, total, real):
#  0.054312   0.002104   0.056416 (  0.056520)

The output displays four timing metrics:

Comparing Code Blocks with Benchmark.bm

When comparing two or more alternative implementations, Benchmark.bm produces a formatted comparison table:

require 'benchmark'

n = 500_000

Benchmark.bm(20) do |x|
  # String concatenation with +=
  x.report("String#+=") do
    str = ""
    n.times { str += "a" }
  end

  # String shovel operator <<
  x.report("String#<<") do
    str = ""
    n.times { str << "a" }
  end

  # Array join
  x.report("Array#join") do
    arr = []
    n.times { arr << "a" }
    arr.join
  end
end

The integer argument passed to Benchmark.bm(20) sets the label column width for clean alignment.

Sample output:

                           user     system      total        real
String#+=              0.843210   0.002100   0.845310 (  0.847120)
String#<<              0.021430   0.000120   0.021550 (  0.021600)
Array#join             0.034500   0.001100   0.035600 (  0.035750)

2. Eliminating Warm-up Skew with Benchmark.bmbm

Dynamic runtimes like Ruby allocate memory and warm up caches during early iterations. The Benchmark.bmbm method runs a rehearsal pass first to force memory allocation and garbage collection before running the actual measured benchmark:

require 'benchmark'

iterations = 1_000_000

Benchmark.bmbm(15) do |x|
  x.report("map then compact") do
    (1..iterations).map { |i| i.even? ? i : nil }.compact
  end

  x.report("filter_map") do
    (1..iterations).filter_map { |i| i if i.even? }
  end
end

bmbm displays two sections:

  1. Rehearsal: Warms up objects and triggers initial GC.
  2. Benchmark: The actual measured timing for reliable comparison.

3. Iterations Per Second with benchmark-ips

While standard Benchmark measures wall-clock time for a fixed number of iterations, the industry-standard benchmark-ips gem measures how many times a snippet can run per second. It automatically handles warmup, statistical sampling, and confidence intervals:

gem install benchmark-ips
require 'benchmark/ips'

Benchmark.ips do |x|
  # Configure warmup time and calculation time (optional)
  x.config(time: 5, warmup: 2)

  data = (1..10_000).to_a

  x.report("find") do
    data.find { |v| v == 9_999 }
  end

  x.report("bsearch") do
    data.bsearch { |v| v >= 9_999 }
  end

  # Compare results directly
  x.compare!
end

Sample output:

ruby 4.0.7 (2026-09-15 revision 229531a6cf) +PRISM [x64-mingw-ucrt]
Warming up --------------------------------------
                find     2.145k i/100ms
             bsearch   148.520k i/100ms
Calculating -------------------------------------
                find     21.842k (± 2.1%) i/s   (45.78 μs/i) -    110.145k in   5.045231s
             bsearch      1.821M (± 1.9%) i/s  (549.02 ns/i) -      9.152M in   5.027814s

Comparison:
bsearch:  1821432.1 i/s
   find:    21842.3 i/s - 83.39x  slower

compare! automatically ranks solutions and calculates speedup multiples.


4. Measuring Memory Allocations

CPU time is only one dimension of performance; garbage collection pressure caused by excessive object allocations is often the primary bottleneck in Ruby applications.

Using GC.stat to Track Allocations

You can track total allocations before and after running code:

def measure_allocations
  GC.disable
  before = GC.stat(:total_allocated_objects)
  yield
  after = GC.stat(:total_allocated_objects)
  GC.enable
  after - before
end

allocations = measure_allocations do
  Array.new(10_000) { "hello" }
end

puts "Objects allocated: #{allocations}"

Profiling with ObjectSpace

Ruby's built-in objspace library measures the exact byte size of memory occupied by objects:

require 'objspace'

str = "Performance"
puts "Memory used: #{ObjectSpace.memsize_of(str)} bytes"

5. Benchmarking Best Practices and Pitfalls

  1. Beware of Garbage Collection Variance: When measuring CPU-intensive algorithms, either run with bmbm or disable GC temporarily using GC.disable / GC.enable (ensure you re-enable GC afterwards).
  2. Avoid Micro-benchmarking Non-representative Data: Ensure dataset sizes reflect real-world scenarios (e.g., testing with 10 elements may favor an O(n) array scan, while 100,000 elements favor an O(1) hash lookup).
  3. Ruby 3+ JIT Considerations: If running Ruby with YJIT (ruby --yjit), include adequate warmup cycles so the JIT compiler has time to compile hot code paths before measurement begins.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents