Guest User

Untitled

a guest
Apr 20th, 2018
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.27 KB | None | 0 0
  1. #!/usr/bin/env ruby
  2. require 'time'
  3. require 'benchmark'
  4.  
  5. class Thing
  6. attr_accessor :timestamp
  7. def initialize(timestamp)
  8. @timestamp = timestamp
  9. end
  10.  
  11. def self.next_time(i)
  12. time = Time.now - (i * 60)
  13. time.iso8601(3)
  14. end
  15. end
  16.  
  17.  
  18. def generate_things(count = 100)
  19. things = []
  20. 1.upto(count) do |i|
  21. things << Thing.new(Thing.next_time(i))
  22. end
  23. things
  24. end
  25.  
  26. def merge(l, r)
  27. l, r = l.dup, r.dup
  28. x = []
  29. while x.length < 25 and l.length > 0 and r.length > 0
  30. if l.at(0).timestamp >= r.at(0).timestamp
  31. x.push l.shift
  32. else
  33. x.push r.shift
  34. end
  35. end
  36. return x if x.length >= 25
  37.  
  38. if l.length > 0
  39. x.concat l
  40. else
  41. x.concat r
  42. end
  43. x
  44. end
  45.  
  46. def nocopy_merge(l, r)
  47. lcount, rcount = l.size, r.size
  48. lin, rin = 0, 0
  49. x = []
  50. while lin+rin < 25 and lin < lcount and rin < rcount
  51. if l.at(lin).timestamp >= r.at(rin).timestamp
  52. x.push l.at(lin)
  53. lin += 1
  54. else
  55. x.push r.at(rin)
  56. rin += 1
  57. end
  58. end
  59. return x if lin+rin == 25
  60.  
  61. if lin < lcount
  62. x.concat l[lin, lcount]
  63. else
  64. x.concat r[rin, rcount]
  65. end
  66. x
  67. end
  68.  
  69. one = generate_things
  70. two = generate_things
  71.  
  72. Benchmark.bmbm(10) do |x|
  73. x.report("merge:") { 50_000.times { merge(one, two) } }
  74. x.report("nocopy:") { 50_000.times { nocopy_merge(one, two) } }
  75. end
Add Comment
Please, Sign In to add comment