58

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.

1

1 Answer 1

61

In Python 2.7, -O has the following effect:

In 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

Sign up to request clarification or add additional context in comments.

8 Comments

Is there any downside to the -O flag apart from missing on the built-in debugging information?
I've seen many python modules that assume docstrings are available, and would break if that optimization level is used, for instance at the company where I work, raw sql is placed in docstrings, and executed by way of function decorators (not even kidding). Somewhat less frequently, assert is used to perform logic functions, rather than merely declare the invariant expectations of a point in code, and so any code like that would also break.
@max: if you go through the complete list of semantical changes above: do you consider any of them a "downside"? If not, there are no downsides. I personally consider it a disadvantage that the name of byte code files changes - it contributes to disk clutter. Notice that "missing built-in debugging information" is not in the list; pdb continues to work fine (this was not the case in earlier Python releases, where -O dropped support for single-stepping in pdb).
@max: in general, I wouldn't expect any significant change in speed. Optimized byte code was originally designed to drop the inefficient SETLINENO byte code instruction, which was needed for single-stepping. However, single-stepping since got reimplemented using a more efficient approach, so -O has lost its point.
At least in current CPython versions, __debug__ doesn't just get changed to False, any code under if __debug__ is entirely stripped out.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.