栏目分类:
子分类:
返回
文库吧用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
文库吧 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

%e
/usr/bin/time
格式为:

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

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

#!/usr/bin/env pythonimport osimport timefrom subprocess import check_call, STDOUTDEVNULL = 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 pythonimport osimport timefrom subprocess import Popen, STDOUTDEVNULL = 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() - startprint(" {:.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 pythonimport osfrom collections import dequefrom subprocess import Popen, PIPEDEVNULL = open(os.devnull, 'wb', 0)time_lines_count = 1 # how many lines /usr/bin/time producesp = 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).depre().strip())

或将

-o
选项与命名管道一起使用:

#!/usr/bin/env pythonimport osfrom contextlib import contextmanagerfrom shutil     import rmtreefrom subprocess import Popen, STDOUTfrom tempfile   import mkdtempDEVNULL = open(os.devnull, 'wb', 0)@contextmanagerdef 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)


转载请注明:文章转载自 www.wk8.com.cn
本文地址:https://www.wk8.com.cn/it/640286.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 wk8.com.cn

ICP备案号:晋ICP备2021003244-6号