Python inner loop imports are 3x slower than file-level imports
This benchmark script tests inner loop imports instead of outside imports. The results show that inner loop imports are about 3x slower than file-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()Results
example.txt
Time (import outside loop): 0.0786 sec
Time (import inside loop): 0.2162 sec
Import inside loop is 3x slower than importing outside.on Core i7-6700, with Python 3.12.3 on
Check out similar posts by category:
Python
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow