Python 循环内导入比文件级导入慢约 3 倍
这个基准测试脚本测试的是循环内导入而非外部导入。结果显示,循环内导入比文件级导入慢约 3 倍。
import_benchmark.py
import time
import sys
def benchmark_import_outside():
"""对在循环外导入 math 模块进行基准测试。"""
import math # 在循环外导入一次
start = time.time()
for _ in range(1_000_000):
x = math.sqrt(100) # 使用已导入的模块
end = time.time()
return end - start
def benchmark_import_inside():
"""对在循环内导入 math 模块进行基准测试。"""
start = time.time()
for _ in range(1_000_000):
import math # 在循环内导入(不良实践)
x = math.sqrt(100)
end = time.time()
return end - start
def clear_math_from_cache():
"""从 sys.modules 中清除 math 模块以强制重新加载。"""
if 'math' in sys.modules:
del sys.modules['math']
def main():
# 基准测试前确保 math 未被缓存
clear_math_from_cache()
# 对外部导入进行基准测试
time_outside = benchmark_import_outside()
print(f"Time (import outside loop): {time_outside:.4f} sec")
# 从缓存中清除 math 以确保公平比较
clear_math_from_cache()
# 对内部导入进行基准测试
time_inside = benchmark_import_inside()
print(f"Time (import inside loop): {time_inside:.4f} sec")
# 计算并打印性能差异
ratio = time_inside / time_outside
print(f"Import inside loop is {ratio:.0f}x slower than importing outside.")
if __name__ == "__main__":
main()结果
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.测试环境为 Core i7-6700,Python 3.12.3,运行于
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