Python 中异常处理程序的成本 [英] Cost of exception handlers in Python

查看:18
本文介绍了Python 中异常处理程序的成本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

另一个问题中,接受的答案建议替换Python 代码中的(非常便宜的)if 语句,带有 try/except 块以提高性能.

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

撇开编码风格问题不谈,假设异常从未被触发,有一个异常处理程序与没有一个异常处理程序相比有多大区别(性能方面)与一个比较为零的 if 语句?

Coding style issues aside, and assuming that the exception is never triggered, how much difference does it make (performance-wise) to have an exception handler, versus not having one, versus having a compare-to-zero if-statement?

推荐答案

为什么不使用 timeit 模块?这样您就可以了解它是否与您的应用程序相关.

Why don't you measure it using the timeit module? That way you can see whether it's relevant to your application.

好的,所以我刚刚尝试了以下操作:

OK, so I've 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 = {}
{}".format(a,s))
        print("%.2f usec/pass
" % (1000000 * t.timeit(number=100000)/100000))

结果:

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

所以,正如预期的那样,没有任何异常处理程序会稍微快一些(但是当异常发生时会在你面前炸开),并且 try/except 比显式的 if 只要不满足条件.

So, as expected, not having any exception handler is slightly faster (but blows up in your face when the exception happens), and try/except is faster than an explicit if as long as the condition is not met.

但这一切都在同一个数量级内,无论哪种方式都不太可能.只有当条件真正满足时,if 版本会明显更快.

But it's all within the same order of magnitude and unlikely to matter either way. Only if the condition is actually met, then the if version is significantly faster.

这篇关于Python 中异常处理程序的成本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆