Python 3 子进程比等效的 bash 慢



我正在使用python3脚本来自动化某些作业。 我需要测量此类外部工作的时间。所以我决定使用 python 3 内置的 time(( 和子进程模块:

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 代码段计算的运行时间为 0.73 秒

但是,等效的 bash 命令:

time ./file < input_file > output_file

明显更快:0.5 秒

哪个可能导致这种巨大的差异?也许由于重定向使用而与 python 解释器进行上下文切换?也许与缓冲有关?

没有重定向用法的类似代码不会显示此行为:

start = time.time()
process = subprocess.run(['sleep','1'])
end = time.time()

上述代码时间以 1s + 可忽略不计的时间经过。

此致敬意

这是一个愚蠢的错误。

time.time(( 在大多数系统中没有很好的精度。

请注意,即使时间始终作为浮点数返回,但并非所有系统都提供精度高于 1 秒的时间。虽然此函数通常返回非递减值,但如果系统时钟在两次调用之间设置回去,它可以返回比上一个调用更低的值。 Python 3 时间模块文档

perf_counter(( 或 process_time(( 工作正常。子流程没有错。

最新更新