Skip to content

Instantly share code, notes, and snippets.

@brettinternet
Forked from mattieb/time_del.py
Last active July 10, 2017 20:58
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 brettinternet/dda0498b9d1ba5223d982526141edf50 to your computer and use it in GitHub Desktop.
Save brettinternet/dda0498b9d1ba5223d982526141edf50 to your computer and use it in GitHub Desktop.
Time various methods of removing a possibly-present item from a dict
#!/usr/bin/python3
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 range(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))
@brettinternet
Copy link
Author

brettinternet commented Jul 10, 2017

Here are some results on my work PC's WSL with python3:

pop succeed: 0.618718147277832
pop fail: 0.6250848770141602
try succeed: 0.5316371917724609
try fail: 0.7190759181976318
if succeed: 0.548640251159668
if fail: 0.5335237979888916

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