Skip to content

Instantly share code, notes, and snippets.

@Ptico
Created November 8, 2019 12:58
Show Gist options
  • Save Ptico/5a9dfb8656edec035e73bfde4997046e to your computer and use it in GitHub Desktop.
Save Ptico/5a9dfb8656edec035e73bfde4997046e to your computer and use it in GitHub Desktop.
require 'benchmark'
require 'benchmark/ips'
require 'benchmark/memory'
require 'faker'
class Bench
attr_reader :benchmarks
attr_accessor :bmbm_iters
def initialize
@benchmarks = {}
@bmbm_iters = 10_000
end
def report(name, &code)
@benchmarks[name] = code
end
def run(argv=ARGV)
run_tests
puts
run_bmbm if argv.include?('--bmbm') or argv.include?('--all')
run_ips if argv.include?('--ips') or argv.include?('--all')
run_mem if argv.include?('--mem') or argv.include?('--all')
end
def run_tests
puts '========================'
puts 'Running tests'
puts '========================'
puts
benchmarks.each_pair do |name, code|
puts "# \"#{name}\" returns:"
puts
puts code.call
puts
end
end
def run_bmbm
puts '========================'
puts 'Running Benchmark.bmbm'
puts '========================'
puts
Benchmark.bmbm do |b|
benchmarks.each_pair do |name, code|
b.report(name) do
@bmbm_iters.times do
code.call
end
end
end
end
puts
end
def run_ips
puts '========================'
puts 'Running Benchmark.ips'
puts '========================'
puts
Benchmark.ips do |b|
benchmarks.each_pair do |name, code|
b.report(name, &code)
end
b.compare!
end
puts
end
def run_mem
puts '========================'
puts 'Running Benchmark.memory'
puts '========================'
puts
Benchmark.memory do |b|
benchmarks.each_pair do |name, code|
b.report(name, &code)
end
b.compare!
end
puts
end
end
require_relative './bench'
b = Bench.new
b.report('String#<<') do
s = 'foo'
s << 'bar'
s # It's highly recommended to return a value for inspection and inspect thar results of tests are equal
end
b.report('String#+=') do
s = 'foo'
s += 'bar'
s
end
s.run
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment