Skip to content

Instantly share code, notes, and snippets.

@adam12

adam12/bench_file.rb Secret

Created Oct 18, 2019
Embed
What would you like to do?
require 'benchmark/ips'
require "tempfile"
def Warning.warn(*); end
data = Tempfile.new
100_000.times { |i| data.write "#{i} #{[*?a..?z].sample(7).join}\n" }
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.to_s.split.each_slice(2).map { |pid, prog| [pid.to_i, prog] } }
x.report("with_object") { data.to_s.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
data.close
data.unlink
__END__
Warming up --------------------------------------
lines 11.178k i/100ms
each_slice 13.943k i/100ms
with_object 17.839k i/100ms
each_line 22.733k i/100ms
Calculating -------------------------------------
lines 140.668k (±12.9%) i/s - 693.036k in 5.041439s
each_slice 192.749k (± 7.5%) i/s - 962.067k in 5.022303s
with_object 182.791k (±17.8%) i/s - 874.111k in 5.024672s
each_line 239.246k (±16.3%) i/s - 1.159M in 5.087971s
Comparison:
each_line: 239245.5 i/s
each_slice: 192749.2 i/s - same-ish: difference falls within error
with_object: 182791.0 i/s - same-ish: difference falls within error
lines: 140667.7 i/s - 1.70x 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.