Last active
August 20, 2020 17:34
-
-
Save AlexWayfer/37ebb8b9f3429650b86fb4cea7ae3693 to your computer and use it in GitHub Desktop.
Benchmark example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# frozen_string_literal: true | |
require 'bundler/setup' | |
Bundler.setup :system | |
require 'pry-byebug' | |
require 'benchmark' | |
require 'benchmark/ips' | |
require 'benchmark/memory' | |
puts '```ruby' | |
puts File.read(__FILE__).gsub("\t", ' ') | |
puts '```' | |
puts | |
puts '### Output' | |
puts | |
puts '```' | |
OPTIONS = { a: 1, b: 2, c: 3 }.freeze | |
VARIATIONS = { | |
literal: (lambda do | |
{ a: 1, b: 2, c: 3 } | |
end), | |
constant: (lambda do | |
OPTIONS | |
end) | |
}.freeze | |
def test | |
results = VARIATIONS.each_with_object([]) do |(name, block), array| | |
array << (result = block.call) | |
puts "Result of #{name}:" | |
pp result | |
puts | |
end | |
uniq_size = results.uniq.size | |
puts "Uniq results: #{uniq_size}" | |
puts | |
exit 1 if uniq_size > 1 | |
end | |
test | |
Benchmark.ips do |x| | |
VARIATIONS.each do |name, block| | |
x.report(name) { block.call } | |
end | |
x.compare! | |
end | |
Benchmark.memory do |x| | |
VARIATIONS.each do |name, block| | |
x.report(name) { 100.times { block.call } } | |
end | |
x.compare! | |
end | |
puts '```' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment