首页 > 解决方案 > 如何在 Python 中测量包含延迟的子进程的时间?

问题描述

我有一个包含 2 秒延迟的进程,我正在尝试测量延迟进程在不同程序中运行所需的时间。我尝试了很多不同的时间工具,包括 time.time()、time.clock()、timeit、resource、os.wait4() 等。无论我怎么做,都没有考虑到子进程延迟 2 秒(它们都返回一些非常小的数字,例如 0.00113 ...)。相反,当我在当前程序中运行相同的代码时(而不是测量子进程),它会输出正确的经过时间(类似于 2.002...)。我确定延迟在子进程中正常工作,只是没有正确测量。我的代码如下所示(这只是我尝试过的一种实现,使用 time.time()):

import subprocess

now = time.clock()
response = subprocess.Popen(['python3', 'oracle.py'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
response.wait()
then = time.clock()
time_elapsed = then - now
print("time elapsed: ", str(time_elapsed))```

标签: pythontimesubprocesssleep

解决方案


问题不在于time.clock()不起作用,问题在于您的子进程实际上没有运行 2 秒,或者根本无法运行。

尝试使用subprocess.check_output()而不是subprocess.Popen()让我们知道它显示了什么。这样你就不需要response.wait()了,因为等待和错误检查都是在里面处理的check_output()


推荐阅读