Skip to content

Instantly share code, notes, and snippets.

@mattieb
Last active February 28, 2022 22:02
Show Gist options
  • Save mattieb/6280653 to your computer and use it in GitHub Desktop.
Save mattieb/6280653 to your computer and use it in GitHub Desktop.
Time various methods of removing a possibly-present item from a dict
#!/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)
@RyanCPeters
Copy link

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
case succeed fail
pop 45.673 ms 49.161 ms
try 56.651 ms 72.481 ms
if 58.166 ms 42.423 ms
Table 2: execution times relative to the slowest test case
case succeed fail
pop 63.014% 67.8%
try 78.16% 100.0%
if 80.25% 58.5%

Table 2 data has been rounded to the nearest tenth of a percent (that's about +-70 microseconds for the data from my pc)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment