问题描述
文档只说Python解释器执行基本优化",而没有涉及任何细节.显然,它取决于实现方式,但是有什么方法可以使人们知道可以优化哪种类型的东西,以及可以节省多少运行时间?
The docs only say that Python interpreter performs "basic optimizations", without going into any detail. Obviously, it's implementation dependent, but is there any way to get a feel for what type of things could be optimized, and how much run-time savings it could generate?
使用-O是否有不利之处?
Is there any downside to using -O?
我唯一知道的是-O禁用了assert
,但是对于在生产中仍然可能出错的事情,大概不应该使用assert
.
The only thing I know is that -O disables assert
, but presumably one shouldn't use assert
for things that could still go wrong in production.
推荐答案
在Python 2.7中,-O
具有以下作用:
In Python 2.7, -O
has the following effect:
- 字节码扩展名更改为
.pyo
- sys.flags.optimize设置为1
-
__debug__
是错误的 - 断言不会被执行
- the byte code extension changes to
.pyo
- sys.flags.optimize gets set to 1
__debug__
is False- asserts don't get executed
此外,-OO
具有以下作用:
- sys.flags.optimize设置为2
- 文档字符串不可用
要验证不同版本的CPython的效果,请grep Py_OptimizeFlag
的源代码.
To verify the effect for a different release of CPython, grep the source code for Py_OptimizeFlag
.
链接到官方文档: https://docs.python .org/2.7/tutorial/modules.html#compiled-python-files
这篇关于Python优化(-O或PYTHONOPTIMIZE)有什么作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!