Skip to content

Instantly share code, notes, and snippets.

@bendyorke
Created May 20, 2014 06:54
Show Gist options
  • Save bendyorke/924612cba7432cbf36dd to your computer and use it in GitHub Desktop.
Save bendyorke/924612cba7432cbf36dd to your computer and use it in GitHub Desktop.
Benchmarking sampling of a hash
require "benchmark"
n = 10000
arr = (1..1000).to_a
zip = arr.zip arr
hash = Hash[zip]
Benchmark.bm do |x|
x.report("%-30s" %["sampling array"]) { n.times do
arr.sample
end }
x.report("%-30s" %["creating hash"]) { n.times do
Hash[zip]
end }
x.report("%-30s" %["sampling hash with #[] 1"]) { n.times do
Hash[ hash.to_a.sample(1) ]
end }
x.report("%-30s" %["sampling hash with #to_h 1"]) { n.times do
hash.to_a.sample(1).to_h
end }
x.report("%-30s" %["sampling hash with #[] 10"]) { n.times do
Hash[ hash.to_a.sample(10) ]
end }
x.report("%-30s" %["sampling hash with #to_h 10"]) { n.times do
hash.to_a.sample(10).to_h
end }
x.report("%-30s" %["sampling hash with #[] 100"]) { n.times do
Hash[ hash.to_a.sample(100) ]
end }
x.report("%-30s" %["sampling hash with #to_h 100"]) { n.times do
hash.to_a.sample(100).to_h
end }
x.report("%-30s" %["sampling hash with #[] 1000"]) { n.times do
Hash[ hash.to_a.sample(1000) ]
end }
x.report("%-30s" %["sampling hash with #to_h 1000"]) { n.times do
hash.to_a.sample(1000).to_h
end }
end
user system total real
sampling array 0.000000 0.000000 0.000000 ( 0.000946)
creating hash 2.730000 0.130000 2.860000 ( 2.865713)
sampling hash with #[] 1 0.790000 0.010000 0.800000 ( 0.789821)
sampling hash with #to_h 1 0.730000 0.000000 0.730000 ( 0.735309)
sampling hash with #[] 10 0.770000 0.000000 0.770000 ( 0.764275)
sampling hash with #to_h 10 0.770000 0.000000 0.770000 ( 0.772692)
sampling hash with #[] 100 1.020000 0.000000 1.020000 ( 1.021916)
sampling hash with #to_h 100 1.020000 0.000000 1.020000 ( 1.021014)
sampling hash with #[] 1000 3.530000 0.010000 3.540000 ( 3.536519)
sampling hash with #to_h 1000 3.540000 0.000000 3.540000 ( 3.541142)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment