This flag enables Profile guided optimization (PGO) and Link Time Optimization (LTO).

Both are expensive optimizations that slow down the build process but yield a significant speed boost (around 10-20% from what I remember reading).

The discussion of what these exactly do is beyond my knowledge and probably too broad for a single question. Either way, you can read a bit about LTO from the the docs on GCC which has an implementation for it and get a start on PGO by reading its wiki page.

Also, see the relevant issues opened on the Python Bug Tracker that added these:

  • Issue 24915: Profile Guided Optimization improvements (better training, llvm support, etc) (Added PGO.)
  • Issue 25702: Link Time Optimizations support for GCC and CLANG (Added LTO.)
  • Issue 26359: CPython build options for out-of-the box performance (Adds the --enable-optimizations flag to the configure script which enables the aforementioned optimizations.)

As pointed out by @Shuo in a comment and stated in Issue 28032, LTO isn't always enabled with the --enable-optimizations flag. Some platforms (depending on the supported version of gcc) will disable it in the configuration script.

Future versions of this flag will probably always have it enabled though, so it's pretty safe to talk about them both here.

Answer from Dimitris Fasarakis Hilliard on Stack Overflow
🌐
AppSignal
blog.appsignal.com › 2025 › 05 › 28 › ways-to-optimize-your-code-in-python.html
Ways to Optimize Your Code in Python | AppSignal Blog
May 28, 2025 - Optimized algorithms: Experienced developers highly optimize standard library functions to perform common tasks efficiently. Reduced overhead: Invoking a function implemented in C avoids the overhead associated with Python's dynamic typing and ...
Discussions

What is the use of Python's basic optimizations mode? (python -O) - Stack Overflow
Python has a flag -O that you can execute the interpreter with. The option will generate "optimized" bytecode (written to .pyo files), and given twice, it will discard docstrings. From Python's man... More on stackoverflow.com
🌐 stackoverflow.com
Activating Python's optimization mode via script-level command-line argument - Stack Overflow
I have a script which loads various modules to do its job. Some of these modules are heavily studded with assert statements - enough to potentially cause significant slow-downs in actual use. (I'm ... More on stackoverflow.com
🌐 stackoverflow.com
How to optimize python code?
Profiling. Don't even consider trying to optimise the performance of your code until you've got data on which stuff is slow. Most code isn't critical to performance, even in applications with hard-to-hit performance requirements, and it's a waste of time trying to tune the stuff that doesn't matter. Use a profiler to figure out which of your code is taking the most time, and once you know that, focus on that code. My favourite profiler right now is Py-Spy, but if you've only got the standard library at your disposal, cProfile is a good start. More on reddit.com
🌐 r/Python
157
177
January 28, 2022
optimization - What are the implications of running python with the optimize flag? - Stack Overflow
What does Python do differently when running with the -O (optimize) flag? More on stackoverflow.com
🌐 stackoverflow.com
🌐
Python
wiki.python.org › moin › PythonSpeed › PerformanceTips
PythonSpeed/PerformanceTips - Python Wiki
It's often useful to place them inside functions to restrict their visibility and/or reduce initial startup time. Although Python's interpreter is optimized to not import the same module multiple times, repeatedly executing an import statement can seriously affect performance in some circumstances.
🌐
Stackify
stackify.com › how-to-optimize-python-code
Best Method of Python Code Optimization - Stackify - Ivanov
September 16, 2023 - Let’s start by defining code optimization, so that you get the basic idea and understand why it’s needed. Sometimes it’s not enough to create code that just executes the task.
🌐
SciPy
docs.scipy.org › doc › scipy › reference › generated › scipy.optimize.minimize.html
minimize — SciPy v1.17.0 Manual
The name of the parameter must ... an OptimizeResult. These methods will also terminate if the callback raises StopIteration. All methods except trust-constr (also) support a signature like: ... Introspection is used to determine which of the signatures above to invoke...
🌐
Stack Abuse
stackabuse.com › python-performance-optimization
Python Performance Optimization
February 21, 2019 - Again, in small-scale scripts, it might not make much difference, but optimization comes good at a larger scale, and in that situation, such memory saving will come good and allow us to use the extra memory saved for other operations.
Find elsewhere
🌐
Google
developers.google.com › or-tools › get started with or-tools for python
Get Started with OR-Tools for Python | Google for Developers
June 5, 2025 - Users need to identify their problem type and choose the appropriate solver to find the optimal solution. Python programs using OR-Tools typically involve importing libraries, declaring the solver, defining variables, constraints, and the objective function, and then invoking the solver to ...
🌐
SOFTFORMANCE
softformance.com › home › blog › 25 tips for optimizing python performance
Optimizing Python Code for Performance: Tips & Tricks | SoftFormance
January 10, 2024 - Run the command line script, activate cProfile as an argument, and use Python’s “-m” option. Using generators is one more way to optimize memory consumption.
🌐
CopyProgramming
copyprogramming.com › howto › what-does-enable-optimizations-do-while-compiling-python
Python Enable Optimizations: Complete Guide to Compilation, Features, and 2026 Best Practices
October 16, 2025 - The -O flag removes assert statements and sets the __debug__ variable to False, while -OO performs all -O optimizations plus removes docstrings from your compiled modules. These flags create optimized .pyc files marked with an opt- tag, significantly reducing bytecode size for production deployments. When you run python -O your_script.py, the interpreter skips all assertion checks entirely—no validation code is executed.
🌐
Reddit
reddit.com › r/python › how to optimize python code?
r/Python on Reddit: How to optimize python code?
January 28, 2022 -

Hi Pythonistas,

I'm interested in learning what optimization techniques you know for python code. I know its a general statement, but I'm interested in really pushing execution to the maximum.

I use the following -

  1. I declare __slots__ in custom classes

  2. I use typing blocks for typing imports

  3. I use builtins when possible

  4. I try to reduce function calls

  5. I use set lookups wherever possible

  6. I prefer iteration to recursion

Edit: I am using a profiler, and benchmarks. I'm working on a library - an ASGI Api framework. The code is async. Its not darascience. Its neither compatible with pypy, nor with numba..

What else?

🌐
Stack Overflow
stackoverflow.com › questions › 52033607 › python-optimize-script
Python Optimize Script? - Stack Overflow
>>> C:\Users\da74\Desktop\sites\pinscraper\ps>python -W ignore scrape.py --url https://www.pinterest.com/vijayakumargana/classic-kuala-lumpur/ --fname classic_kl.csv Ghost Driver Invoked Started Scroling ... Scrolled: 11124 Scrolled: 18388 Total Pins: 126 Dynamic Elements: 125 Display: Dynamic Elements ...
Top answer
1 of 16
47

Regarding "Secondly: When writing a program from scratch in python, what are some good ways to greatly improve performance?"

Remember the Jackson rules of optimization:

  • Rule 1: Don't do it.
  • Rule 2 (for experts only): Don't do it yet.

And the Knuth rule:

  • "Premature optimization is the root of all evil."

The more useful rules are in the General Rules for Optimization.

  1. Don't optimize as you go. First get it right. Then get it fast. Optimizing a wrong program is still wrong.

  2. Remember the 80/20 rule.

  3. Always run "before" and "after" benchmarks. Otherwise, you won't know if you've found the 80%.

  4. Use the right algorithms and data structures. This rule should be first. Nothing matters as much as algorithm and data structure.

Bottom Line

You can't prevent or avoid the "optimize this program" effort. It's part of the job. You have to plan for it and do it carefully, just like the design, code and test activities.

2 of 16
30

Rather than just punting to C, I'd suggest:

Make your code count. Do more with fewer executions of lines:

  • Change the algorithm to a faster one. It doesn't need to be fancy to be faster in many cases.
  • Use python primitives that happens to be written in C. Some things will force an interpreter dispatch where some wont. The latter is preferable
  • Beware of code that first constructs a big data structure followed by its consumation. Think the difference between range and xrange. In general it is often worth thinking about memory usage of the program. Using generators can sometimes bring O(n) memory use down to O(1).
  • Python is generally non-optimizing. Hoist invariant code out of loops, eliminate common subexpressions where possible in tight loops.
  • If something is expensive, then precompute or memoize it. Regular expressions can be compiled for instance.
  • Need to crunch numbers? You might want to check numpy out.
  • Many python programs are slow because they are bound by disk I/O or database access. Make sure you have something worthwhile to do while you wait on the data to arrive rather than just blocking. A weapon could be something like the Twisted framework.
  • Note that many crucial data-processing libraries have C-versions, be it XML, JSON or whatnot. They are often considerably faster than the Python interpreter.

If all of the above fails for profiled and measured code, then begin thinking about the C-rewrite path.

🌐
Gregoryszorc
gregoryszorc.com › blog › 2019 › 01 › 10 › what-i've-learned-about-optimizing-python
Gregory Szorc's Digital Home | What I've Learned About Optimizing Python
January 10, 2019 - Python has a relatively complex mechanism for resolving attributes. For simple types, it can be quite fast. But for complex types, that attribute access can silently be invoking __getattr__, __getattribute__, various other dunder methods, and even custom @property functions.
🌐
DataCamp
datacamp.com › tutorial › optimization-in-python
Optimization in Python: Techniques, Packages, and Best Practices | DataCamp
August 31, 2024 - Discover the Python coding best practices for writing best-in-class Python scripts. ... This Python cheat sheet is a quick reference for NumPy beginners. ... Unlock the power of Bayesian Optimization for hyperparameter tuning in Machine Learning.
🌐
Medium
medium.com › @quanticascience › performance-optimization-in-python-e8a497cdaf11
Performance Optimization in Python | by QuanticaScience | Medium
February 24, 2024 - However, with the right techniques, Python’s performance can be significantly optimized. This article delves into various strategies for enhancing Python code efficiency, from understanding its performance characteristics to employing concurrency and advanced optimization techniques.
🌐
SciPy
docs.scipy.org › doc › scipy › tutorial › optimize.html
Optimization (scipy.optimize) — SciPy v1.17.0 Manual
The implementations shown in the following sections provide examples of how to define an objective function as well as its jacobian and hessian functions. Objective functions in scipy.optimize expect a numpy array as their first parameter which is to be optimized and must return a float value.