大佬教程收集整理的这篇文章主要介绍了带/ usr / bin / time的Python子进程:如何捕获时序信息,但忽略所有其他输出?,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
%e
/usr/bin/time
格式为:
要使用抑制的stdout / stderr运行子进程并获取经过的时间:
#!/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
在Python
2上的POSIX上使用的,因此您应该有一个有效的时间,除非您的使用timeit
不正确。
resource
模块返回的信息 不 包括“实时”时间,但是您可以使用它来获取“用户”和“ sys”时间,即“进程在用户模式下花费的cpu秒总数”。 和 “进程在内核模式下花费的cpu秒总数”。 相应地:
#!/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))
您可以使用 子进程 以可移植的方式 运行子进程并运行 其他信息(cpu,内存,网络连接,线程,fds, 子进程等)
来psutil.Popen
获取 子进程 。
为了进行测试(以确保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())
或将-o
选项与命名管道一起使用:
#!/usr/bin/env python
import os
from contextlib import contextmanager
from shutil import rmtree
from subprocess import Popen, STDOUT
from tempfile import mkdtemp
DEVNulL = open(os.devnull, 'wb', 0)
@contextmanager
def named_pipe():
dirname = mkdtemp()
try:
path = os.path.join(dirname, 'named_pipe')
os.mkfifo(path)
yIEld path
finally:
rmtree(dirName)
with named_pipe() as path:
p = Popen(['/usr/bin/time', '--format=%e seconds', '-o', path] +
['sleep', '1'], stdout=DEVNulL, stderr=STDOUT)
with open(path) as file:
time_output = file.read().Strip()
rc = p.wait()
print(time_output)
我试图以秒为单位来衡量通过子流程调用的可执行程序的执行时间。我不希望发出可执行文件(stderr或stdout)的输出。
我已经尝试了timeit和资源库,但是都没有准确地捕获进程的时间,似乎它只捕获了Python worker线程中的时间。
下面的这种尝试将丢失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的输出?
以上是大佬教程为你收集整理的带/ usr / bin / time的Python子进程:如何捕获时序信息,但忽略所有其他输出?全部内容,希望文章能够帮你解决带/ usr / bin / time的Python子进程:如何捕获时序信息,但忽略所有其他输出?所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。