Python-Imports in inneren Schleifen sind 3x langsamer als Datei-Level-Imports

Dieses Benchmark-Skript testet Imports in inneren Schleifen statt außerhalb. Die Ergebnisse zeigen, dass Imports in inneren Schleifen etwa 3x langsamer sind als Datei-Level-Imports.

import_benchmark.py
import time
import sys

def benchmark_import_outside():
    """Benchmark importing math module outside the loop."""
    import math  # Import once outside the loop

    start = time.time()
    for _ in range(1_000_000):
        x = math.sqrt(100)  # Use the imported module
    end = time.time()

    return end - start

def benchmark_import_inside():
    """Benchmark importing math module inside the loop."""
    start = time.time()
    for _ in range(1_000_000):
        import math  # Import inside the loop (bad practice)
        x = math.sqrt(100)
    end = time.time()

    return end - start

def clear_math_from_cache():
    """Clear math module from sys.modules to force reload."""
    if 'math' in sys.modules:
        del sys.modules['math']

def main():
    # Ensure math is not cached before benchmarking
    clear_math_from_cache()

    # Benchmark outside import
    time_outside = benchmark_import_outside()
    print(f"Time (import outside loop): {time_outside:.4f} sec")

    # Clear math from cache to ensure fair comparison
    clear_math_from_cache()

    # Benchmark inside import
    time_inside = benchmark_import_inside()
    print(f"Time (import inside loop): {time_inside:.4f} sec")

    # Calculate and print the performance difference
    ratio = time_inside / time_outside
    print(f"Import inside loop is {ratio:.0f}x slower than importing outside.")

if __name__ == "__main__":
    main()

Ergebnisse

benchmark_output.txt
Time (import outside loop): 0.0786 sec
Time (import inside loop): 0.2162 sec
Import inside loop is 3x slower than importing outside.

auf Core i7-6700, mit Python 3.12.3 auf


Check out similar posts by category: Python