public
Created

new benchmark with a "Meier" method added

  • Download Gist
gistfile1.txt
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
require 'benchmark'
 
n = 2
#ar = [4,5,6,4,5,6,6,7]
maxval = 1000
ar = [].tap{|a| 1_000_000.times {a << rand(maxval)}}
puts "SAMPLE of ar"
puts ar[0...20]
puts "SIZE"
puts ar.size
puts "MAXVAL"
puts maxval
 
Benchmark.bm(15) do |b|
b.report("Ralph Shnelvar:"){ n.times { result = Hash.new(0); ar.each { |x| result[x] += 1 }; result} }
b.report("Sigurd:") { n.times { ar.inject(Hash.new(0)) {|res, x| res[x] += 1; res } } }
 
b.report("Meier:") {
n.times {
hist = Array.new(maxval+1, 0)
ar.each{|x| hist[x] += 1;}
result = Hash.new(0)
0.upto(maxval){|i| result[i] = hist[i] unless hist[i] == 0}
result
}
}
 
b.report("Keinich #1") { n.times { Hash[ar.group_by{|n|n}.map{|k,v|[k, v.size]}] } }
b.report("Keinich #2") { n.times { Hash.new(0).tap{|h|ar.each{|n|h[n] += 1}} } }
b.report("Magnus Holm:") { n.times { ar.each_with_object(Hash.new(0)) { |x, res| res[x] += 1 } } }
b.report("Abinoam #1:") { n.times { Hash[ar.sort.chunk {|n| n}.map {|ix, els| [ix, els.size] } ] } }
end

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.