I try to do micro-benchmarks in python as little as possible, but it never hurts to be aware of the cost of your primitive operations. That's regardless of the language you're coding in.
So, today's experiment... Say you want to remove a key from a dict whether it exists or not. How long does it take? Depends on your method of choice...
pop: 0.24 usec/pass try/except: 2.27 usec/pass if in: 0.11 usec/pass if has_key: 0.20 usec/pass
if x in d: del d[x] wins for execution time, but there are definitely times when the (almost 20x!) overhead of exception can be worth it.
import timeit
num = 10000
a = {}
setup = """
a = {}
"""
stmt = """
a.pop("hi", None)
"""
t = timeit.Timer(stmt=stmt, setup=setup)
print "pop: %.2f usec/pass" % (1000000 * t.timeit(number=num)/num)
stmt = """
try:
del a['hi']
except KeyError:
pass
"""
t = timeit.Timer(stmt=stmt, setup=setup)
print "try/except: %.2f usec/pass" % (1000000 * t.timeit(number=num)/num)
stmt = """
if 'hi' in {}:
del a['hi']
"""
t = timeit.Timer(stmt=stmt, setup=setup)
print "if in: %.2f usec/pass" % (1000000 * t.timeit(number=num)/num)
stmt = """
if {}.has_key('hi'):
del a['hi']
"""
t = timeit.Timer(stmt=stmt, setup=setup)
print "if has_key: %.2f usec/pass" % (1000000 * t.timeit(number=num)/num)
Be the first to reply!
Post a Comment
By submitting a comment you assert that it is your own original work and agree to grant a non-exclusive licence to Brandon Thomson to display it on log.bthomson.com.