Cost of exception handlers in Python

In another question , the accepted answer suggested replacing the (very cheap) if statement in Python code with a try / except block to improve performance.

Problems with coding aside, and assuming that the exception never fires, what difference does it make (in terms of performance) of having an exception handler compared to the absence of one of them compared to the if-statement metric of zero

+44
performance python exception micro-optimization
Mar 26 '10 at 8:52
source share
3 answers

Why don't you measure it using the timeit module ? This way you can find out if this applies to your application.

OK, so I just tried the following:

 import timeit statements=["""\ try: b = 10/a except ZeroDivisionError: pass""", """\ if a: b = 10/a""", "b = 10/a"] for a in (1,0): for s in statements: t = timeit.Timer(stmt=s, setup='a={}'.format(a)) print("a = {}\n{}".format(a,s)) print("%.2f usec/pass\n" % (1000000 * t.timeit(number=100000)/100000)) 

Result:

 a = 1 try: b = 10/a except ZeroDivisionError: pass 0.25 usec/pass a = 1 if a: b = 10/a 0.29 usec/pass a = 1 b = 10/a 0.22 usec/pass a = 0 try: b = 10/a except ZeroDivisionError: pass 0.57 usec/pass a = 0 if a: b = 10/a 0.04 usec/pass a = 0 b = 10/a ZeroDivisionError: int division or modulo by zero 

So, as expected, the absence of an exception handler is a little faster (but it will explode on your face when an exception occurs), and try/except faster than the explicit if , until the condition is met.

But all this is in the same order and hardly matters in any case. Only if the condition is indeed met does the if version execute much faster.

+61
Mar 26 '10 at 8:54
source share

Frequently asked questions on design and history really answer this question:

The try / except block is extremely efficient if no exceptions are thrown. Actually catching an exception is expensive.

+30
Mar 27
source share

This question is misleading. If you think that the exception never fires, none of them is the best code.

If you think that an exception is triggered as part of the error condition, you are already outside the scope of the search for the optimal code (and you probably won't process it at the same fine-grained level).

If you use an exception as part of the standard control flow - this is Pythonic's “ask for forgiveness, not permission”, then the exception will be raised, and the cost depends on the type of exception, the type of if, and what percentage of the time you evaluate the exception.

+9
Sep 18 '10 at 21:12
source share



All Articles