Skip to content

Instantly share code, notes, and snippets.

@pzelnip
Created June 18, 2012 21:50
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 pzelnip/2950940 to your computer and use it in GitHub Desktop.
Save pzelnip/2950940 to your computer and use it in GitHub Desktop.
Showing that try/except is slower than isinstance
'''
Example showing that isinstance checks are faster than doing a "it's better to ask for forgiveness than
permission approach.
'''
from timeit import Timer
# Silly timing code that can be ignored
def timeruns(runs, num_iterations = 100):
return [(label, Timer(cmd, imports).timeit(num_iterations))
for cmd, imports, label in runs]
def format_runs(runresults):
result = "Timing Results:\n%s\n" % ("-" * 20)
minlabel, mintime = "Arbitrary label", 12319283719827319.0
maxlabel, maxtime = "Arbitrary label", -1.0
for label, time in runresults:
result += "%s : %s\n" % (label, time)
if time < mintime:
mintime = time
minlabel = label
if time > maxtime:
maxtime = time
maxlabel = label
result += "%s\n" % ("-" * 20)
per_faster = round((1.0 - mintime / maxtime) * 100)
result += ("Fastest time: %s - %s (%s%% faster than slowest)\n" %
(minlabel, mintime, per_faster))
result += "Slowest time: %s - %s\n" % (maxlabel, maxtime)
return result
# Do an eq using try/except on AttributeError
class Foo(object):
def __init__(self, val):
self.val = val
def __eq__(self, other):
try:
return other.val == self.val
except AttributeError:
return NotImplemented
# Do an eq using a simple isinstance check
class Bar(object):
def __init__(self, val):
self.val = val
def __eq__(self, other):
if isinstance(other, Bar):
return other.val == self.val
return NotImplemented
if __name__ == "__main__":
setup = """
from __main__ import Foo, Bar
f = Foo(42)
b = Bar(42)
"""
num_iter = 1000000
runs = [("f == '42kldfj'", setup, "doing exception"),
("b == '42kldfj'", setup, "doing isinstance")]
print(format_runs(timeruns(runs, num_iter)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment