带有/ usr / bin / time的Python子进程:如何捕获时序信息,但忽略所有其他输出?

问题描述 投票:2回答:2

我正在尝试通过子流程调用可执行程序的执行时间(以秒为单位)。我不希望发出可执行文件(stderr或stdout)的输出。

我已经尝试了timeit和资源库,但是都没有准确地捕获进程的时间,似乎只捕获了Python工作线程中的时间。

以下尝试将丢失stderr重定向的时间信息b / c。但是,如果没有stderr重定向,将发出命令'f_cmd'stderr输出。

def doWithTiming(f_cmd):
    DEVNULL = open(os.devnull, 'w')
    return subprocess.check_output([ "/usr/bin/time", "--format=%e seconds"] + f_cmd.split(), stderr=DEVNULL)

我如何忽略f_cmd的所有输出,但保留/ usr / bin / time的输出?

python python-2.7 time stdout stderr
2个回答
6
投票

%e /usr/bin/time format is

进程使用的实际(墙上时钟)经过的时间,以秒为单位。

要使用抑制的stdout / stderr运行子进程并获得经过的时间:

%e

[/usr/bin/time在Python 2的POSIX上为#!/usr/bin/env python import os import time from subprocess import check_call, STDOUT DEVNULL = open(os.devnull, 'wb', 0) start = time.time() check_call(['sleep', '1'], stdout=DEVNULL, stderr=STDOUT) print("{:.3f} seconds".format(time.time() - start)) ,因此,除非您对timeit.default_timer的使用不正确,否则您应该有一个有效的时间。


time.time模块返回的信息不包含[[not,包括“真实”时间,但是您可以使用它来获取“用户”和“ sys”时间,即“ CPU秒总数在用户模式下花费的进程。“”在内核模式下花费的CPU秒总数。“相应地:

timeit

您可以使用resource启动子进程并以可移植的方式获取

在子进程运行时

其他信息(CPU,内存,网络连接,线程,fds,子进程等)。>另请参见,#!/usr/bin/env python import os import time from subprocess import Popen, STDOUT DEVNULL = open(os.devnull, 'wb', 0) start = time.time() p = Popen(['sleep', '1'], stdout=DEVNULL, stderr=STDOUT) ru = os.wait4(p.pid, 0)[2] elapsed = time.time() - start print(" {:.3f}real {:.3f}user {:.3f}system".format( elapsed, ru.ru_utime, ru.ru_stime))


为了进行测试(以确保基于psutil.Popen的解决方案产生相同的结果,您可以捕获How to get the max memory usage of a program using psutil in Python输出:

time.time()

或在命名管道中使用/usr/bin/time选项:

#!/usr/bin/env python import os from collections import deque from subprocess import Popen, PIPE DEVNULL = open(os.devnull, 'wb', 0) time_lines_count = 1 # how many lines /usr/bin/time produces p = Popen(['/usr/bin/time', '--format=%e seconds'] + ['sleep', '1'], stdout=DEVNULL, stderr=PIPE) with p.stderr: q = deque(iter(p.stderr.readline, b''), maxlen=time_lines_count) rc = p.wait() print(b''.join(q).decode().strip())


0
投票
您的问题与Python无关,而与Linux时间实用程序的行为无关。进程写入任何stderr消息后,时间将写入stderr。您将获得从外壳运行它的效果。子进程将精确复制shell命令的行为。
© www.soinside.com 2019 - 2024. All rights reserved.