Guest User

Untitled

a guest
Apr 22nd, 2018
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.83 KB | None | 0 0
  1. require 'benchmark'
  2.  
  3. SOURCE_DATA = [
  4. {:name => 'host', :id => 1},
  5. {:name => 'problem', :id => 3},
  6. {:name => 'host_outage', :id => 4},
  7. {:name => 'host', :id => 5},
  8. {:name => 'host', :id => 2},
  9. {:name => 'host_outage', :id => 2},
  10. {:name => 'host', :id => 7},
  11. {:name => 'problem', :id => 4},
  12. {:name => 'host_outage', :id => 7}
  13. ]
  14.  
  15. def working_base
  16. names = SOURCE_DATA.collect{ |a| a[:name] }
  17. names.uniq.collect do |n|
  18. {:name => n, :count => names.grep(n).size}
  19. end
  20. end
  21.  
  22. def first_attempt
  23. counts = {}
  24. SOURCE_DATA.each do |a|
  25. counts[a[:name]] ||= 0
  26. counts[a[:name]] += 1
  27. end
  28. counts
  29. end
  30.  
  31. def first_attempt_with_format
  32. counts = {}
  33. SOURCE_DATA.each do |a|
  34. counts[a[:name]] ||= 0
  35. counts[a[:name]] += 1
  36. end
  37.  
  38. names = []
  39. counts.each_pair do |k,v|
  40. names << { :name => k, :count => v }
  41. end
  42. names
  43. end
  44.  
  45. def second_attempt
  46. counts = []
  47. SOURCE_DATA.each do |a|
  48. c = counts.find { |c| c[:name] == a[:name] }
  49. c.nil? ? counts << { :name => a[:name], :count => 1 } : counts[counts.index(c)][:count] += 1
  50. end
  51. counts
  52. end
  53.  
  54. def hendrik_1
  55. result = {}
  56. SOURCE_DATA.each do |a|
  57. if result[a[:name]].nil?
  58. result[a[:name]] = 1
  59. else
  60. result[a[:name]] = result[a[:name]] + 1
  61. end
  62. end
  63. result
  64. end
  65.  
  66. RUNS = 10_000
  67.  
  68. Benchmark.benchmark do |dm|
  69. puts ""
  70.  
  71. dm.report { RUNS.times { working_base } }
  72. puts working_base.inspect
  73. puts ""
  74.  
  75. dm.report { RUNS.times { first_attempt } }
  76. puts first_attempt.inspect
  77. puts ""
  78.  
  79. dm.report { RUNS.times { first_attempt_with_format } }
  80. puts first_attempt_with_format.inspect
  81. puts ""
  82.  
  83. dm.report { RUNS.times { second_attempt } }
  84. puts second_attempt.inspect
  85. puts ""
  86.  
  87. dm.report { RUNS.times { hendrik_1 } }
  88. puts hendrik_1.inspect
  89. puts ""
  90. end
Add Comment
Please, Sign In to add comment