python - 如何在 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))```
解决方案
问题不在于time.clock()
不起作用,问题在于您的子进程实际上没有运行 2 秒,或者根本无法运行。
尝试使用subprocess.check_output()
而不是subprocess.Popen()
让我们知道它显示了什么。这样你就不需要response.wait()
了,因为等待和错误检查都是在里面处理的check_output()
。
推荐阅读
- python - 错误:安装 pandas-profiling 期间需要 Microsoft Visual C++ 14.0 或更高版本
- python - ctypes结构中数组元素的赋值
- neo4j - neo4j 结合多个关系并动态创建一个新关系
- apache-superset - 使用 Apache Superset 启用自定义错误页面(例如 404)的最佳方法是什么?
- html - 使用右对齐或左对齐的最佳方式
- date - 如何在数组公式中添加带有 where 日期条件的查询?
- java - ProgressDialog android studio的模糊背景
- php - 将此 XML 数据转换为 JSON 格式的最简单方法
- zapier - 将 API 与 Zapier 一起使用,但获取“应用程序返回”“rest_data”参数不正确。需要 JSON 数据“。”
- postgresql - 在 Postgres 表中使用时区保存日期时间