Is try-except slow?

Steven D'Aprano steven at REMOVE.THIS.cybersource.com.au
Wed Sep 3 07:43:19 CEST 2008


On Tue, 02 Sep 2008 18:56:48 -0500, Robert Kern wrote:

> ssecorp wrote:
>> or why does this take so god damn long time?
> 
> Several reasons. One of which is that try: except: is slow.


I beg to differ. Setting up a try...except block is very fast. Here's an 
example in Python 2.5:


>>> from timeit import Timer
>>> Timer('len("abc")').repeat()
[0.27346706390380859, 0.1530919075012207, 0.14886784553527832]
>>> Timer('''try:
...     len("abc")
... except:
...     pass
... ''').repeat()
[0.27847194671630859, 0.19191384315490723, 0.19077491760253906]

The difference (approx 0.04 microseconds) applicable to setting up the 
try...except block is trivial, of the same magnitude as a pass statement:

>>> Timer('pass').repeat()
[0.059719085693359375, 0.060056924819946289, 0.059512138366699219]


However, *catching* the exception may be relatively slow:

>>> Timer('''try:
...     len(abc)  # raise a NameError
... except:
...     pass
... ''').repeat()
[3.2067418098449707, 2.7088210582733154, 1.9558219909667969]



-- 
Steven




More information about the Python-list mailing list