Skip to content

Instantly share code, notes, and snippets.

@petervandenabeele
Created January 23, 2012 14:42
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save petervandenabeele/1663455 to your computer and use it in GitHub Desktop.
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