Skip to content

Instantly share code, notes, and snippets.

@the5fire
Created June 19, 2018 11:56
Show Gist options
  • Save the5fire/3ecd37ed8b1648b455c30f73fd5d37f4 to your computer and use it in GitHub Desktop.
Save the5fire/3ecd37ed8b1648b455c30f73fd5d37f4 to your computer and use it in GitHub Desktop.
# ref:https://stackoverflow.com/a/20308693/938077
from timeit import timeit
size = 2**10
allkeys = "0% missing keys", dict([(i, 0) for i in range(size)])
somekeys = "50% missing keys", dict([(i*2, 0) for i in range(size//2)])
nokeys = "100% missing keys", dict([])
def test_normal():
"""Standard access"""
for i in range(size):
v = d.get(i)
if not v:
d[i] = 1
def test_try():
"""try/except access"""
for i in range(size):
try:
v = d[i]
except KeyError:
d[i] = 1
for trial in (allkeys, somekeys, nokeys):
d = trial[1]
for test in (test_try, test_normal):
trial_time = timeit("test()",
setup="from __main__ import test",
number=2**10)
print("{0}, {1}: {2}".format(trial[0], test.__doc__, trial_time))
'''
output:
0% missing keys, try/except access: 0.11592264400678687
0% missing keys, Standard access: 0.2794266320124734
50% missing keys, try/except access: 0.15932855699793436
50% missing keys, Standard access: 0.2333725259959465
100% missing keys, try/except access: 0.14439084999321494
100% missing keys, Standard access: 0.24631450600281823
'''
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment