4.1. Optimization About

  • python -O - remove docstrings in addition to the optimizations performed by python -O; also sets __debug__ to False

  • python -OO - optimize generated bytecode slightly; also sets __debug__ to False

Premature optimization is the root of all evil. -- Donald Knuth

../../_images/performance-optimization-knuth.jpg

Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live. -- John Woods

Python was not optimized for speed, but for readability and maintainability. -- Guido van Rossum

4.1.1. Optimization Flag

  • python -O - remove assert statements and any code conditional on the value of __debug__; also sets __debug__ to False

  • python -OO - remove docstrings in addition to the optimizations performed by python -O

"""
This is a docstring for the module.
"""

class MyClass:
    """
    This is a docstring for the class.
    """

    def my_method(self):
        """
        This is a docstring for the method.
        """
        pass


def add(a, b):
    """
    This is a docstring for the function.
    """
    assert isinstance(a, int), 'Argument `a` must be an integer.'
    assert isinstance(b, int), 'Argument `b` must be an integer.'
    return a + b

if __debug__:
    import sys; sys.tracebacklimit = 0
    assert sys.version_info >= (3, 15), 'Python 3.15 or newer is required.'


result = add(1, 2)
print(f'Result: {result}')

print(f'Debug: {__debug__}')

print(f'Docstring Module: {__doc__}')
print(f'Docstring Class: {MyClass.__doc__}')
print(f'Docstring Method: {MyClass.my_method.__doc__}')
print(f'Docstring Function: {add.__doc__}')
$ python main.py
Result: 3
Debug: True
Docstring Module:
This is a docstring for the module.

Docstring Class:
This is a docstring for the class.

Docstring Method:
This is a docstring for the method.

Docstring Function:
This is a docstring for the function.
$ python -O main.py
Result: 3
Debug: False
Docstring Module:
This is a docstring for the module.

Docstring Class:
This is a docstring for the class.

Docstring Method:
This is a docstring for the method.

Docstring Function:
This is a docstring for the function.
$ python -OO main.py
Result: 3
Debug: False
Docstring Module: None
Docstring Class: None
Docstring Method: None
Docstring Function: None

4.1.2. Types

  • Performance Optimization

  • Memory Optimization

  • Disk Space Optimization

  • Disk Usage Optimization (I/O Operations)

  • Network Optimization

  • Energy Optimization

  • Cost Optimization

  • Time Optimization

  • Code Optimization

4.1.3. Levels

  • Design Optimization

  • Algorithm Optimization

  • Data Structure Optimization

  • Source Code Optimization

  • Build Level Optimization

  • Compile Level Optimization

  • Runtime Level Optimization