Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the implications of running python with the optimize flag?

I cannot seem to find a good simple explanation of what python does differently when running with the -O or optimize flag.

like image 914
kkubasik Avatar asked May 13 '10 21:05

kkubasik


People also ask

What is Python optimized for?

Python code optimization is a way to make your program perform any task more efficiently and quickly with fewer lines of code, less memory, or other resources involved, while producing the right results. It's crucial when it comes to processing a large number of operations or data while performing a task.

Does Python have compiler optimization?

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.

What does Python optimization (- O or Pythonoptimize do?

To verify the effect for a different release of CPython, grep the source code for Py_OptimizeFlag .


2 Answers

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.

like image 55
Alex Martelli Avatar answered Sep 30 '22 10:09

Alex Martelli


From the docs:

When the Python interpreter is invoked with the -O flag, optimized code is generated and stored in .pyo files. The optimizer currently doesn’t help much; it only removes assert statements. When -O is used, all bytecode is optimized; .pyc files are ignored and .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. Currently only __doc__ strings are removed from the bytecode, resulting in more compact .pyo files. Since some programs may rely on having these available, you should only use this option if you know what you’re doing.

A program doesn’t run any faster when it is read from a .pyc or .pyo file than when it is read from a .py file; the only thing that’s faster about .pyc or .pyo files is the speed with which they are loaded.

So in other words, almost nothing.

like image 42
ire_and_curses Avatar answered Sep 30 '22 10:09

ire_and_curses