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

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

问题描述

另一个问题中,接受的答案建议替换一个(非常便宜的)if语句在Python代码中带有一个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 = {}\n{}".format(a,s))
        print("%.2f usec/pass\n" % (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 比一个显式的更快,如果

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.

但是这一切都在同一个数量级上,不太可能会有任何关系。只有实际满足条件,那么如果版本明显更快。

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天全站免登陆