Skip to content

Instantly share code, notes, and snippets.

@gr33n7007h

gr33n7007h/bench Secret

Created Oct 18, 2019
Embed
What would you like to do?
benchmark
☺️ /home/gr33n7007h $ cat benchmark.rb
require 'benchmark/ips'
data = 100_000.times.map { |i| "#{i} #{[*?a..?z].sample(7).join}\n" }.join
iter = 100
Benchmark.ips do |x|
x.report("lines") { iter.times { data.lines.map{ |line| line.split }.map{ |pid, prog| [pid.to_i, prog] } } }
x.report("each_slice") { iter.times { data.split.each_slice(2).map { |pid, prog| [pid.to_i, prog] } } }
x.report("with_object") { iter.times { data.split.each_slice(2).with_object([]) { |(pid, prog), container| container << [pid.to_i, prog] } } }
x.report("each_line") { iter.times { data.each_line.map { |line| line.split.yield_self {|pid, prog| [pid.to_i, prog] } } } }
x.compare!
end
☺️ /home/gr33n7007h $ ruby benchmark.rb
Warming up --------------------------------------
lines 1.000 i/100ms
each_slice 1.000 i/100ms
with_object 1.000 i/100ms
each_line 1.000 i/100ms
Calculating -------------------------------------
lines 0.158 (± 0.0%) i/s - 1.000 in 6.348481s
each_slice 0.195 (± 0.0%) i/s - 1.000 in 5.131357s
with_object 0.175 (± 0.0%) i/s - 1.000 in 5.709754s
each_line 0.127 (± 0.0%) i/s - 1.000 in 7.846839s
Comparison:
each_slice: 0.2 i/s
with_object: 0.2 i/s - 1.11x slower
lines: 0.2 i/s - 1.24x slower
each_line: 0.1 i/s - 1.53x slower
☺️ /home/gr33n7007h $
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.