问题描述
文档只说 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__
是假的- 断言不会被执行
另外-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)有什么作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!