Skip to content

Instantly share code, notes, and snippets.

@phlco
Last active December 21, 2015 19:19
Show Gist options
  • Save phlco/6353537 to your computer and use it in GitHub Desktop.
Save phlco/6353537 to your computer and use it in GitHub Desktop.
ruby benchmarking template
##############
### Benchmarks
##############
require 'benchmark'
# http://www.ruby-doc.org/stdlib-1.9.3/libdoc/benchmark/rdoc/Benchmark.html
# http://rubylearning.com/blog/2013/06/19/how-do-i-benchmark-ruby-code/
# http://stackoverflow.com/questions/556405/what-do-real-user-and-sys-mean-in-the-output-of-time1/556411#556411
iterations = 100_000 # How many times to test?
# when doing benchmarks that test code that executes very quickly,
# you need to do many iterations to see a meaningful number.
# (20) is padding for headers
Benchmark.bmbm(20) do |bm|
# `bmbm` first runs the code as a 'rehearsal' to force any initialization that needs to happen,
# then it forces the GC to run, then it runs the benchmark again 'for real'.
# This ensures that the system is fully initialized and the benchmark is fair.
# First Attempt
bm.report('Challenger 1') do
iterations.times do
# Code goes here
end
end
# Second Attempt
bm.report('Challenger 2') do
iterations.times do
# Code goes here
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment