Skip to content

Instantly share code, notes, and snippets.

@adam12

adam12/bench.rb Secret

Created Oct 18, 2019
Embed
What would you like to do?
require 'benchmark/ips'
data = 100_000.times.map { |i| "#{i} #{[*?a..?z].sample(7).join}\n" }.join
Benchmark.ips do |x|
x.report("lines") { data.lines.map{ |line| line.split }.map{ |pid, prog| [pid.to_i, prog] } }
x.report("each_slice") { data.split.each_slice(2).map { |pid, prog| [pid.to_i, prog] } }
x.report("with_object") { data.split.each_slice(2).with_object([]) { |(pid, prog), container| container << [pid.to_i, prog] } }
x.report("each_line") { data.each_line.map { |line| line.split.yield_self {|pid, prog| [pid.to_i, prog] } } }
x.compare!
end
__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
adam12 run
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 11.603 (±17.2%) i/s - 56.000 in 5.028396s
each_slice 15.135 (±19.8%) i/s - 72.000 in 5.038677s
with_object 13.945 (±14.3%) i/s - 69.000 in 5.049401s
each_line 10.265 (± 9.7%) i/s - 51.000 in 5.046033s
Comparison:
each_slice: 15.1 i/s
with_object: 13.9 i/s - same-ish: difference falls within error
lines: 11.6 i/s - same-ish: difference falls within error
each_line: 10.3 i/s - 1.47x slower
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.