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

8
  • 1
    Is there any downside to the -O flag apart from missing on the built-in debugging information?
    – max
    Jan 24, 2011 at 2:17
  • 14
    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. Jan 24, 2011 at 3:12
  • 1
    @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). Jan 24, 2011 at 7:43
  • 13
    @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. Jan 27, 2011 at 6:01
  • 11
    At least in current CPython versions, __debug__ doesn't just get changed to False, any code under if __debug__ is entirely stripped out.
    – kindall
    Nov 18, 2013 at 16:57

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.