【发布时间】:2017-08-19 21:22:10
【问题描述】:
我正在使用 python3 脚本来自动化一些工作。 我需要测量这些外部工作的时间。所以我决定使用 python 3 内置的 time() 结合 subprocess 模块:
with open(in_files[i],'r') as f, open(sol_files[i],'w') as f_sol:
start = time.time()
process = subprocess.run(['./'+src_files[i]], stdin = f, stdout=f_sol)
end = time.time()
这个python sn-p计算的经过时间是0.73秒
但是,等效的 bash 命令:
time ./file < input_file > output_file
明显更快:0.5 秒
是什么原因导致了这种巨大的差异?也许由于重定向使用而与 python 解释器进行上下文切换?也许与缓冲有关?
没有重定向用法的类似代码不会显示此行为:
start = time.time()
process = subprocess.run(['sleep','1'])
end = time.time()
上述代码时间经过了 1s + 可忽略的时间。
最好的问候
【问题讨论】:
-
我不会认为 0.5 秒比 0.73 秒明显快。您是否多次重复测量?也许运行时间的波动甚至比你观察到的差异还要大。
-
是的,我做到了。结果是一样的。 STDev 可以忽略不计。最好的问候
标签: python bash python-3.x process benchmarking