【问题标题】:Python 3 subprocesses slower than equivalent bashPython 3 子进程比等效 bash 慢
【发布时间】: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


【解决方案1】:

这是一个愚蠢的错误。

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

请注意,尽管时间总是以浮点数形式返回,但并非所有系统都提供比 1 秒更好的时间精度。虽然此函数通常返回非递减值,但如果系统时钟已在两次调用之间调回,则它可以返回比先前调用更低的值。 Python 3 Time Module Documentation

perf_counter() 或 process_time() 工作得很好。子流程没有错。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-25
    • 1970-01-01
    • 1970-01-01
    • 2012-01-29
    • 2019-06-28
    相关资源
    最近更新 更多