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?
Is there any downside to using -O?
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.
To verify the effect for a different release of CPython, grep the source code for Py_OptimizeFlag .
Python can run scripts in optimized mode ( python -O ) which turns off debugs, removes assert statements, and IIRC it also removes docstrings. I have not seen it used. Maybe it is just an artifact of past times.
py files are compiled to optimized bytecode. Passing two -O flags to the Python interpreter (-OO) will cause the bytecode compiler to perform optimizations that could in some rare cases result in malfunctioning programs.
So, in general CPython does not try very hard to optimize anything - actually, it doesn't seem to do any kind of "smart" code analysis, AFAICT they mostly try to build an efficient but "mostly vanilla" interpreter. So, expect to pay almost exactly for what you write, there's no optimizer to save sloppy code.
In Python 2.7, -O
has the following effect:
.pyo
__debug__
is FalseIn addition -OO
has the following effect:
To verify the effect for a different release of CPython, grep the source code for Py_OptimizeFlag
.
Link to official documentation: https://docs.python.org/2.7/tutorial/modules.html#compiled-python-files
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With