Skip to content

Instantly share code, notes, and snippets.

@abinoam
Created January 17, 2012 01:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save abinoam/1624016 to your computer and use it in GitHub Desktop.
Save abinoam/1624016 to your computer and use it in GitHub Desktop.
require 'benchmark'
n = 100_000
ar = [4,5,6,4,5,6,6,7]
Benchmark.bm(15) do |b|
b.report("Ralph Shneiver:"){ 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("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
@abinoam
Copy link
Author

abinoam commented Jan 17, 2012

                user     system      total        real

Ralph Shneiver: 0.290000 0.000000 0.290000 ( 0.259640)
Sigurd: 0.320000 0.000000 0.320000 ( 0.289873)
Keinich #1 0.560000 0.000000 0.560000 ( 0.497736)
Keinich #2 0.280000 0.000000 0.280000 ( 0.250843)
Magnus Holm: 0.310000 0.000000 0.310000 ( 0.283344)
Abinoam #1: 1.140000 0.000000 1.140000 ( 1.042744)

Abinoam Jr.

@petervandenabeele
Copy link

A modified version that creates a large dataset (and fewer iterations over the test):

require 'benchmark'

n = 1
#ar = [4,5,6,4,5,6,6,7]
ar = [].tap{|a| 10_000_000.times {a << rand(100)}}
puts "SAMPLE of ar"
puts ar[0...20]
puts "SIZE"
puts ar.size
Benchmark.bm(15) do |b|
 b.report("Ralph Shneiver:"){ 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("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