Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ## result
- user system total real
- jj 2.650000 0.020000 2.670000 ( 2.697979)
- joekarma 1.840000 0.010000 1.850000 ( 1.871773)
- b_jones 5.280000 0.040000 5.320000 ( 5.365322)
- apeiros 0.880000 0.010000 0.890000 ( 0.890512)
- ## code
- require 'benchmark'
- string = <<EOF
- This is the test string.
- I'm putting text in here because, well,
- I need to fill up a string in order to perform tests
- with it.
- I wonder whos function will fair the best?
- Time will tell!
- EOF
- def line_at_pos(pos, str)
- pos = str.length + pos if pos < 0
- pos = 0 if pos < 0
- l = (str.rindex(/[\r\n]/, pos) || -1) + 1
- r = (str.index(/[\r\n]/, pos) || str.length) - 1
- str[l..r]
- end
- def line_at_pos_2(pos, str)
- str.inject(pos) { |pos, line| break line.chomp if line.length >= pos ; pos - line.length }
- end
- def line_at_pos_3(pos, str)
- str[/\A.{0,#{pos}}^(.*?)$/m, 1]
- end
- def line_at_pos_4(pos, str)
- str[from=(str.rindex("\n", pos)||-1)+1,(str.index("\n",pos)-from)]
- end
- $times = 100000
- Benchmark.bm(10) do |bm|
- bm.report('jj') do
- $times.times do
- line_at_pos_2(rand(string.length), string)
- end
- end
- bm.report('joekarma') do
- $times.times do
- line_at_pos(rand(string.length), string)
- end
- end
- bm.report('b_jones') do
- $times.times do
- line_at_pos_3(rand(string.length), string)
- end
- end
- bm.report('apeiros') do
- $times.times do
- line_at_pos_4(rand(string.length), string)
- end
- end
- end
Add Comment
Please, Sign In to add comment