Benchmark Ruby code for performance comparison and profiling
Profiles Ruby code performance using benchmarks, memory profiling, and comparative analysis.
/plugin marketplace add bastos/ruby-plugin-marketplace/plugin install ruby@ruby-plugin-marketplace[file or code block]Profile and compare Ruby code performance.
The user may provide:
For simple timing:
require "benchmark"
time = Benchmark.measure do
# Code to benchmark
end
puts time
require "benchmark/ips"
Benchmark.ips do |x|
x.config(warmup: 2, time: 5)
x.report("implementation A") do
# First implementation
end
x.report("implementation B") do
# Second implementation
end
x.compare!
end
require "memory_profiler"
report = MemoryProfiler.report do
# Code to analyze
end
report.pretty_print
require "stackprof"
StackProf.run(mode: :cpu, out: "tmp/stackprof.dump") do
# Code to profile
end
# Then analyze with:
# stackprof tmp/stackprof.dump --text
When creating a benchmark file:
#!/usr/bin/env ruby
# frozen_string_literal: true
require "bundler/setup"
require "benchmark/ips"
require_relative "../lib/my_gem"
# Setup data
data = Array.new(1000) { rand(100) }
Benchmark.ips do |x|
x.config(warmup: 2, time: 5)
x.report("Array#each") do
result = []
data.each { |n| result << n * 2 }
end
x.report("Array#map") do
data.map { |n| n * 2 }
end
x.compare!
end
Benchmark.ips do |x|
x.report("interpolation") { "Hello, #{name}!" }
x.report("concatenation") { "Hello, " + name + "!" }
x.report("format") { format("Hello, %s!", name) }
x.compare!
end
Benchmark.ips do |x|
x.report("each + push") do
result = []
items.each { |i| result.push(i * 2) }
end
x.report("map") { items.map { |i| i * 2 } }
x.compare!
end
array = (1..1000).to_a
hash = array.to_h { |n| [n, true] }
set = Set.new(array)
Benchmark.ips do |x|
x.report("Array#include?") { array.include?(500) }
x.report("Hash#key?") { hash.key?(500) }
x.report("Set#include?") { set.include?(500) }
x.compare!
end
Explain benchmark results:
Before running benchmarks, check for required gems:
# Check for benchmark-ips
bundle info benchmark-ips 2>/dev/null || echo "Add 'gem benchmark-ips' to Gemfile"
# Check for memory_profiler
bundle info memory_profiler 2>/dev/null || echo "Add 'gem memory_profiler' to Gemfile"
# Check for stackprof
bundle info stackprof 2>/dev/null || echo "Add 'gem stackprof' to Gemfile"
/ruby:benchmark # Suggest optimizations for current code
/ruby:benchmark benchmarks/array_ops.rb # Run benchmark file
/ruby:benchmark "map vs each for filtering" # Generate comparison benchmark