Skip to content

Instantly share code, notes, and snippets.

@net

net/benchmark.rb Secret

Created October 30, 2015 23:49
Show Gist options
  • Save net/9de3d3705ebba21a9ad1 to your computer and use it in GitHub Desktop.
Save net/9de3d3705ebba21a9ad1 to your computer and use it in GitHub Desktop.
# Pretty bad ruby, I know. I was trying to best simulate how the actual logging in my app works.
require 'benchmark/ips'
DEBUG = true
puts "DEBUG #{DEBUG}"
def do_something(message)
end
def with_block(message=nil)
if DEBUG
message = yield if block_given?
do_something(message)
end
end
def without_block(message)
do_something(message) if DEBUG
end
def with_sprintf(format, *args)
do_something(sprintf(format, *args)) if DEBUG
end
Benchmark.ips do |x|
a = 1234567
y = 'asdfghjkl'
x.report('With block') { with_block { "a debug message with vars #{a} #{y}" } }
x.report('Without block') { without_block("a debug message with vars #{a} #{y}") }
x.report('Sprintf') { with_sprintf("a debug message with vars %s %s", a, y) }
x.compare!
end
# Results
#
# DEBUG false
# Calculating -------------------------------------
# With block 141.188k i/100ms
# Without block 70.933k i/100ms
# Sprintf 116.124k i/100ms
# -------------------------------------------------
# With block 6.554M (± 4.8%) i/s - 32.756M
# Without block 1.186M (± 4.6%) i/s - 5.958M
# Sprintf 3.397M (± 4.4%) i/s - 16.954M
#
# Comparison:
# With block: 6554147.8 i/s
# Sprintf: 3397093.3 i/s - 1.93x slower
# Without block: 1185686.7 i/s - 5.53x slower
#
# DEBUG true
# Calculating -------------------------------------
# With block 62.681k i/100ms
# Without block 67.755k i/100ms
# Sprintf 53.071k i/100ms
# -------------------------------------------------
# With block 1.040M (± 2.7%) i/s - 5.203M
# Without block 1.157M (± 2.5%) i/s - 5.827M
# Sprintf 798.734k (± 3.3%) i/s - 4.033M
#
# Comparison:
# Without block: 1156603.9 i/s
# With block: 1040241.2 i/s - 1.11x slower
# Sprintf: 798734.4 i/s - 1.45x slower
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment