Guest User

Untitled

a guest
Feb 21st, 2018
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.25 KB | None | 0 0
  1. ##result
  2. user system total real
  3. jj 3.130000 0.130000 3.260000 ( 7.560419)
  4. joekarma 2.110000 0.080000 2.190000 ( 4.912987)
  5. b_jonas 4.640000 0.190000 4.830000 ( 19.871645)
  6.  
  7. ##code
  8. require 'benchmark'
  9.  
  10. string = <<EOF
  11. This is the test string.
  12. I'm putting text in here because, well,
  13. I need to fill up a string in order to perform tests
  14. with it.
  15.  
  16. I wonder whos function will fair the best?
  17.  
  18. Time will tell!
  19. EOF
  20.  
  21. def line_at_pos(pos, str)
  22. pos = str.length + pos if pos < 0
  23. pos = 0 if pos < 0
  24. l = (str.rindex(/[\r\n]/, pos) || -1) + 1
  25. r = (str.index(/[\r\n]/, pos) || str.length) - 1
  26. str[l..r]
  27. end
  28.  
  29. def line_at_pos_2(pos, str)
  30. str.inject(pos) { |pos, line| break line.chomp if line.length >= pos ; pos - line.length }
  31. end
  32.  
  33. def line_at_pos_3(pos, str)
  34. (str =~ /\A.{0,#{pos}}^(?-m:.*)/m)[1]
  35. end
  36.  
  37. $times = 100000
  38. Benchmark.bm(10) do |bm|
  39. bm.report('jj') do
  40. $times.times do
  41. line_at_pos_2(rand(string.length), string)
  42. end
  43. end
  44. bm.report('joekarma') do
  45. $times.times do
  46. line_at_pos(rand(string.length), string)
  47. end
  48. end
  49. bm.report('b_jonas') do
  50. $times.times do
  51. line_at_pos_3(rand(string.length), string)
  52. end
  53. end
  54. end
Add Comment
Please, Sign In to add comment