开发者

What are the implications of running python with the optimize flag? [duplicate]

This question already has answers here: What is the use of the "-O" flag for running Python? 开发者_C百科 (4 answers) Closed 4 months ago.

What does Python do differently when running with the -O (optimize) flag?


assert statements are completely eliminated, as are statement blocks of the form if __debug__: ... (so you can put your debug code in such statements blocks and just run with -O to avoid that debug code).

With -OO, in addition, docstrings are also eliminated.


From the docs:

  • You can use the -O or -OO switches on the Python command to reduce the size of a compiled module. The -O switch removes assert statements, the -OO switch removes both assert statements and __doc__ strings. Since some programs may rely on having these available, you should only use this option if you know what you’re doing. “Optimized” modules have an opt- tag and are usually smaller. Future releases may change the effects of optimization.
  • A program doesn’t run any faster when it is read from a .pyc file than when it is read from a .py file; the only thing that’s faster about .pyc files is the speed with which they are loaded.

So in other words, almost nothing.


From What does the -O flag do?

It somewhat depends on the Python version. To find out precisely what it does, search the source code for Py_OptimizeFlag. In 2.5, it

  • causes the interpreter to load .pyo files, not .pyc files (in .zip files, just makes .pyo preferred over .pyc)
  • causes __debug__ to have a value of 0
  • ignores assert statements in source code
  • treats __debug__ statically as being 0
  • causes the byte code generator to save .pyo files, not .pyc


As answered in python optimization mode:

python -O does the following currently:

  • completely ignores asserts
  • sets the special builtin name __debug__ to False (which by default is True)

and when called as python -OO

  • removes docstrings from the code

I don't know why everyone forgets to mention the __debug__ issue; perhaps it is because I'm the only one using it :) An if __debug__ construct creates no bytecode at all when running under -O, and I find that very useful.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜