Last active
February 28, 2022 22:02
-
-
Save mattieb/6280653 to your computer and use it in GitHub Desktop.
Time various methods of removing a possibly-present item from a dict
This file contains hidden or 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
#!/usr/bin/python | |
import time | |
def new_d(): | |
return { | |
1: 2, 3: 4, 5: 6, 7: 8, 9: 10, | |
11: 12, 13: 14, 15: 16, 17: 18, 19: 20 | |
} | |
def time_func(iterations, f, *args): | |
start = time.time() | |
for i in xrange(iterations): | |
f(*args) | |
return time.time() - start | |
def try_del(key): | |
d = new_d() | |
try: | |
del d[key] | |
except KeyError: | |
pass | |
def if_del(key): | |
d = new_d() | |
if key in d: | |
del d[key] | |
def pop_del(key): | |
d = new_d() | |
d.pop(key, None) | |
def succeed(f): | |
f(3) | |
def fail(f): | |
f(4) | |
iterations = 1000000 | |
print "pop succeed:", time_func(iterations, succeed, pop_del) | |
print "pop fail:", time_func(iterations, fail, pop_del) | |
print "try succeed:", time_func(iterations, succeed, try_del) | |
print "try fail:", time_func(iterations, fail, try_del) | |
print "if succeed:", time_func(iterations, succeed, if_del) | |
print "if fail:", time_func(iterations, fail, if_del) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Well, I didn't go into nearly the same level of detail, but I did feel like putting the results into a table allowed for easier consideration of what the data could tell us.
I should probably note that the level of precision in these tables is arbitrary, and we can all agree that a single run on my random pc isn't sufficient to warrant these precision levels. I chose to round to these points in case anyone else had a larger data set to compare this small sample against.
Table 1: execution time (in milliseconds) rounded to to the nearest microsecond
Table 2: execution times relative to the slowest test case
Table 2 data has been rounded to the nearest tenth of a percent (that's about +-70 microseconds for the data from my pc)