Created
December 11, 2013 00:35
-
-
Save mschuerig/7903101 to your computer and use it in GitHub Desktop.
Measure the times it takes to access (hit and miss) elements in hashes with up to 2^21 elements.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'benchmark' | |
require 'ascii_charts' | |
def measure | |
GC.disable | |
Benchmark.realtime do | |
yield | |
end | |
ensure | |
GC.enable | |
end | |
def measure_hash_accesses(exp, count, miss = false) | |
exp.times.map do |exponent| | |
size = 2**exponent | |
hash = {} | |
(1..size).each do |n| | |
index = rand | |
hash[index] = rand | |
end | |
keys = hash.keys | |
kick = miss ? 1.0 : 0.0 | |
targets = count.times.map { keys.sample + kick } | |
offset = measure do | |
targets.each do |k| | |
val = k | |
end | |
end | |
access_time = measure do | |
targets.each do |k| | |
val = hash[k] | |
end | |
end | |
[size, access_time - offset] | |
end | |
end | |
def draw(title, times) | |
puts AsciiCharts::Cartesian.new( | |
times, | |
title: title, | |
y_step_size: 0.05, | |
max_y_vals: 1.0, | |
bar: true, | |
hide_zero: true | |
).draw | |
end | |
count = 1_000_000 | |
hit_times = measure_hash_accesses(21, count) | |
draw "#{count} successful hash reads", hit_times | |
miss_times = measure_hash_accesses(21, count, true) | |
draw "#{count} missing hash reads", miss_times |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment