Skip to content

@petervandenabeele /gist:1663455
Created

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
new benchmark with a "Meier" method added
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.