Guest User

Untitled

a guest
Feb 21st, 2018
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.52 KB | None | 0 0
  1. ## result
  2. user system total real
  3. jj 2.650000 0.020000 2.670000 ( 2.697979)
  4. joekarma 1.840000 0.010000 1.850000 ( 1.871773)
  5. b_jones 5.280000 0.040000 5.320000 ( 5.365322)
  6. apeiros 0.880000 0.010000 0.890000 ( 0.890512)
  7.  
  8.  
  9. ## code
  10. require 'benchmark'
  11.  
  12. string = <<EOF
  13. This is the test string.
  14. I'm putting text in here because, well,
  15. I need to fill up a string in order to perform tests
  16. with it.
  17.  
  18. I wonder whos function will fair the best?
  19.  
  20. Time will tell!
  21. EOF
  22.  
  23. def line_at_pos(pos, str)
  24. pos = str.length + pos if pos < 0
  25. pos = 0 if pos < 0
  26. l = (str.rindex(/[\r\n]/, pos) || -1) + 1
  27. r = (str.index(/[\r\n]/, pos) || str.length) - 1
  28. str[l..r]
  29. end
  30.  
  31. def line_at_pos_2(pos, str)
  32. str.inject(pos) { |pos, line| break line.chomp if line.length >= pos ; pos - line.length }
  33. end
  34.  
  35. def line_at_pos_3(pos, str)
  36. str[/\A.{0,#{pos}}^(.*?)$/m, 1]
  37. end
  38.  
  39. def line_at_pos_4(pos, str)
  40. str[from=(str.rindex("\n", pos)||-1)+1,(str.index("\n",pos)-from)]
  41. end
  42.  
  43. $times = 100000
  44. Benchmark.bm(10) do |bm|
  45. bm.report('jj') do
  46. $times.times do
  47. line_at_pos_2(rand(string.length), string)
  48. end
  49. end
  50. bm.report('joekarma') do
  51. $times.times do
  52. line_at_pos(rand(string.length), string)
  53. end
  54. end
  55. bm.report('b_jones') do
  56. $times.times do
  57. line_at_pos_3(rand(string.length), string)
  58. end
  59. end
  60. bm.report('apeiros') do
  61. $times.times do
  62. line_at_pos_4(rand(string.length), string)
  63. end
  64. end
  65. end
Add Comment
Please, Sign In to add comment