gpt4 book ai didi

python - 如何找到多个子流程的执行时间?

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:04:19 25 4
gpt4 key购买 nike

我有一个 Linux 命令列表,我正在使用子进程模块运行每个命令,我需要弄清楚如何找到每个命令的执行时间并在列表或字典中返回执行时间,在在 dict 的情况下,Key 可以是命令名称,value 是以秒为单位的时间。

(Popen object).poll() == 0 完成的那一刻应该确定完成时间。

我正在使用 Python 3.5.2

例如:

import time
import shlex
from subprocess import *`

#list of commands
commands = ['sleep 5', 'ls -l', 'find /usr','sleep 3','uptime']

#executing each command in the list
for command in commands:
cmd = shlex.split(command)
# Need to time this and the moment it is finished executing.
x = Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE)

应该返回/打印:

- Commands   Time(secs)
- sleep 5 5.0004 #whatever the time it takes
- ls -l 0.000 #and so on....

最佳答案

Popen 是穷人的“后台运行”技术。您可以控制该过程,但如果您想以非轮询方式等待它结束,则不能。

如果您不关心输出,只关心执行时间,您可以将每个 subprocess.call(不再需要 Popen)包装在一个线程中,并更新字典命令=>花费的时间

启动线程不会阻塞,但 call 会阻塞,让您更轻松地为执行计时。

import threading,time,subprocess,shlex

time_dict = {}

def time_me(command):
start_time = time.time()
cmd = shlex.split(command)
subprocess.call(cmd)
time_dict[command] = time.time() - start_time

threads = []
commands = ['sleep 5', 'ls -l', 'find /usr','sleep 3','uptime']

for command in commands:
t = threading.Thread(target=time_me,args=(command,))
t.start()
threads.append(t)

for t in threads:
t.join()

print(time_dict)

关于python - 如何找到多个子流程的执行时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50546100/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com