Skip to content

Instantly share code, notes, and snippets.

@DannyBen
Last active September 20, 2019 09:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DannyBen/f05ed2957d9c2610567c7196066f3aeb to your computer and use it in GitHub Desktop.
Save DannyBen/f05ed2957d9c2610567c7196066f3aeb to your computer and use it in GitHub Desktop.
Ruby Benchmark Helper
require 'benchmark'
require 'bundler/inline'
gemfile do
source "https://rubygems.org"
gem 'tty-progressbar'
gem "benchmark-memory"
gem "colsole"
end
class BM
include Colsole
attr_reader :loops
def add(label=:global, &block)
tests[label] = block
end
def run(loops=10)
memory
time loops
end
def memory
say "!txtgrn!Starting memory benchmark"
Benchmark.memory do |x|
tests.each do |label, block|
x.report label, &block
end
x.compare!
end
puts
end
def time(loops=10)
@loops = loops
@results = {}
say "!txtgrn!Starting execution time benchmark (#{loops} loops)"
bar = TTY::ProgressBar.new "Running [:bar]", total: loops * tests.size
loops.times do |i|
tests.each do |label, block|
measure i, label, &block
bar.advance
end
end
report
end
private
def measure(i, label, &block)
time = Benchmark.measure do
block.call i
end
time = time.real
results[label] ||= {}
results[label][:total] ||= 0
results[label][:total] += time
results[label][:average] = results[label][:total] / loops
results[label][:throughput] = loops / results[label][:total]
end
def report
sorted_results = results.sort_by { |k, v| v[:total] }
puts "%35s %16s" % ["average", "throughput"]
sorted_results.each do |label, stats|
puts "%20s %10.3f sec %12.2f cps" % [
label,
stats[:average],
stats[:throughput],
]
end
puts
end
def results
@results ||= {}
end
def tests
@tests ||= {}
end
end

Ruby Benchmark Helper

Usage

require './bm'

bm = BM.new

bm.add(:sleep_long) { sleep 0.1 }
bm.add(:sleep_short) { sleep 0.95 }
bm.add(:sleep_random) { sleep rand(0.1..0.2) }

bm.add(:frozen) { "1" + "hello".freeze }
bm.add(:unfrozen) { "hello" }

# run both memory and time benchmarks, 3 times (default 10)
bm.run 3

# or:
# bm.memory     # run only memory benchmark
# bm.time 5     # run only execution time benchmark, 5 times (default 10)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment