Created
August 30, 2019 08:01
-
-
Save tompng/5acfc6279e66310e25e5b168ef126a62 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def readA io, line_num | |
line_num.times{io.gets} | |
io.gets | |
end | |
def readB io, line_num | |
size=65536 | |
buf=??*size | |
while true | |
io.read size, buf | |
count = buf.count "\n" # こういうの速かったはず | |
if line_num > count | |
line_num -= count | |
else | |
lines = buf.lines | |
line = lines[line_num] | |
if lines.size == line_num + 1 && line[-1] != "\n" | |
return line + io.gets.to_s | |
else | |
return line | |
end | |
end | |
end | |
end | |
def create_file | |
file_name = 'file' | |
return if File.exist? file_name | |
srand 0 | |
File.open file_name, 'w' do |f| | |
1000000.times do |i| | |
size = rand 0..100 | |
f.puts ['[', i, ' ', (i%10).to_s * size, ']'].join | |
end | |
f.write "last-line" | |
end | |
end | |
def withio | |
io = File.open 'file', 'r' | |
yield io | |
ensure | |
io.close | |
end | |
create_file | |
require 'benchmark' | |
p :readA | |
p Benchmark.realtime { withio { |io| readA(io, 10000) } } | |
p Benchmark.realtime { withio { |io| readA(io, 100000) } } | |
p Benchmark.realtime { withio { |io| readA(io, 1000000) } } | |
p :readB | |
p Benchmark.realtime { withio { |io| readB(io, 10000) } } | |
p Benchmark.realtime { withio { |io| readB(io, 100000) } } | |
p Benchmark.realtime { withio { |io| readB(io, 1000000) } } | |
p :sed | |
p Benchmark.realtime { `sed -n '10001{p;q;}' file` } | |
p Benchmark.realtime { `sed -n '100001{p;q;}' file` } | |
p Benchmark.realtime { `sed -n '1000001{p;q;}' file` } | |
__END__ | |
:readA | |
0.00426099996548146 | |
0.04655800003092736 | |
0.4983699999283999 | |
:readB | |
0.0007429999532178044 | |
0.0027410000329837203 | |
0.02360800001770258 | |
:sed | |
0.01061000011395663 | |
0.039450000040233135 | |
0.32519200001843274 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment