Skip to content

Instantly share code, notes, and snippets.

@jsundram
Last active August 29, 2015 14:01
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 jsundram/a0a030d4ae8912403d7b to your computer and use it in GitHub Desktop.
Save jsundram/a0a030d4ae8912403d7b to your computer and use it in GitHub Desktop.
Explore the relationship between Key Miss Rate and timing for Python dicts.
"""
Explore the relationship between Key Miss Rate and time.
i.e. if you are doing a lot of dictionary lookups, how few misses
do you need to get in order to use try/except vs methods without exceptions
run via $ ipython dict_timing.ipy
"""
def a(d, i):
"""Try / Except"""
try:
return d[i]
except KeyError:
return None
def b(d, i):
"""Two lookups"""
if i in d:
return d[i]
return None
def c(d, i):
"""Use Get"""
return d.get(i, None)
d, N = {}, 100
def test(n):
global d, N
print '%2.1f%% Miss Rate' % (100 * float(n) / N)
d = {i: True for i in range(n)}
%timeit [a(d, i) for i in range(N)]
%timeit [b(d, i) for i in range(N)]
%timeit [c(d, i) for i in range(N)]
def main():
test(50)
test(90)
test(95) # Break-even point
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment