Skip to content

Instantly share code, notes, and snippets.

@AlexWayfer
Last active August 20, 2020 17:34
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AlexWayfer/37ebb8b9f3429650b86fb4cea7ae3693 to your computer and use it in GitHub Desktop.
Save AlexWayfer/37ebb8b9f3429650b86fb4cea7ae3693 to your computer and use it in GitHub Desktop.
Benchmark example
# 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