Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ## result
- user system total real
- jj 3.130000 0.130000 3.260000 ( 16.256510)
- joekarma 2.130000 0.070000 2.200000 ( 10.913229)
- b_jones 5.670000 0.250000 5.920000 ( 49.773998)
- apeiros 2.260000 0.090000 2.350000 ( 20.093709)
- ## 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[0,pos].scan(/.*\n/).last
- 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