Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does Python optimization (-O or PYTHONOPTIMIZE) do?

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.

like image 234
max Avatar asked Jan 23 '11 22:01

max


People also ask

What does Python Optimisation (- O or Pythonoptimize do?

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

What is Python optimized mode?

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.

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.

Does the Python interpreter optimize code?

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.


1 Answers

In Python 2.7, -O has the following effect:

  • the byte code extension changes to .pyo
  • sys.flags.optimize gets set to 1
  • __debug__ is False
  • asserts don't get executed

In addition -OO has the following effect:

  • sys.flags.optimize gets set to 2
  • doc strings are not available

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

like image 187
Martin v. Löwis Avatar answered Sep 19 '22 15:09

Martin v. Löwis