Skip to content

Instantly share code, notes, and snippets.

@wils3005
Created October 14, 2018 02:58
Show Gist options
  • Save wils3005/ebe75cd28ae3462414e01bce9b7589b0 to your computer and use it in GitHub Desktop.
Save wils3005/ebe75cd28ae3462414e01bce9b7589b0 to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
require 'benchmark/ips'
require 'securerandom'
class MyClass
FOO = -> { SecureRandom.hex }
def bar
-> { SecureRandom.hex }
end
def baz
@baz ||= -> { SecureRandom.hex }
end
def benchmark
Benchmark.ips do |benchmark|
benchmark.config(time: 10, warmup: 10)
benchmark.report('foo') { FOO.call }
benchmark.report('bar') { bar.call }
benchmark.report('baz') { baz.call }
benchmark.compare!
end
end
end
MyClass.new.benchmark
# Warming up --------------------------------------
# foo 74.303k i/100ms
# bar 51.173k i/100ms
# baz 67.876k i/100ms
# Calculating -------------------------------------
# foo 928.900k (± 2.2%) i/s - 9.288M in 10.003990s
# bar 606.895k (± 1.6%) i/s - 6.090M in 10.036827s
# baz 879.370k (± 3.4%) i/s - 8.824M in 10.049572s
# Comparison:
# foo: 928899.6 i/s
# baz: 879370.1 i/s - same-ish: difference falls within error
# bar: 606895.3 i/s - 1.53x slower
#
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment