简体   繁体   English

获取 python 子进程运行时间

[英]Get python subprocess run time

I am using python to run multiple subprocesses at the same time.我正在使用 python 同时运行多个子进程。

I want to get the run time of each process.我想获得每个进程的运行时间。

I am using the subprocess module.我正在使用subprocess模块。

What I did: I created two separate for loops: The first one for running each process The second waits for all processes to end.我做了什么:我创建了两个单独的for循环:第一个用于运行每个进程第二个等待所有进程结束。

for prcs in batch:
    p = subprocess.Popen([prcs])
    ps.append(p)
for p in ps:
    p.wait()

This code works fine for running the processes simultaneously, but I do not know what to add to it in order to get the run time of each process separately.此代码适用于同时运行进程,但我不知道要添加什么才能分别获取每个进程的运行时间。

Edit: Is there a way to get the run time through the module subprocess?编辑:有没有办法通过模块子进程获取运行时间? For example: runtime = p.runtime()例如:runtime = p.runtime()

I agree with @quamrana that the easiest way to do this would be with threads.我同意@quamrana 的观点,最简单的方法是使用线程。

First, we need to import some standard library modules:首先,我们需要导入一些标准库模块:

import collections
import subprocess
import threading
import time

Instead of a list to store the processes, we use an ordered dictionary to keep track of the processes and their times.我们不是使用列表来存储流程,而是使用有序字典来跟踪流程及其时间。 Since we don't know how long each thread will take, we need some way to keep track of the original order of our {process: time} pairs.由于我们不知道每个线程需要多长时间,我们需要一些方法来跟踪我们的 {process: time} 对的原始顺序。 The threads themselves can be stored in a list.线程本身可以存储在列表中。

ps = collections.OrderedDict()
ts = []

Initializing the value paired to each process as the current time makes the whole thing cleaner, despite the fact that it is generally inadvisable to use the same variable for two different things (in this case, starting time followed by process duration).将与每个进程配对的值初始化为当前时间会使整个事情更清晰,尽管通常不建议将相同的变量用于两个不同的事情(在这种情况下,开始时间后跟过程持续时间)。 The target for our thread simply waits for the thread to finish and updates the ps ordered dictionary from the start time to the process duration.我们线程的目标只是等待线程完成并将 ps 有序字典从开始时间更新到进程持续时间。

def time_p(p):
    p.wait()
    ps[p] = time.time() - ps[p]

for prcs in batch:
    p = subprocess.Popen([prcs])
    ps[p] = time.time()
    ts.append(threading.Thread(target=time_p, args=(p,)))

Now, we just start each of the threads, then wait for them all to complete.现在,我们只需启动每个线程,然后等待它们全部完成。

for t in ts:
    t.start()

for t in ts:
    t.join()

Once they are all complete, we can print out the results for each:一旦它们都完成了,我们就可以打印出每个的结果:

for prcs, p in zip(batch, ps):
    print('%s took %s seconds' % (prcs, ps[p]))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM