%e /usr/bin/time format is:
进程使用的实际(挂钟)时间,以秒为单位。
使用抑制的 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 在 Python 2 上的 POSIX 上是 time.time,因此您应该有一个有效时间,除非您对 timeit 的使用不正确。
resource 模块返回的信息不包含“真实”时间,但您可以使用它来获取“用户”和“系统”时间,即,“总数进程在用户模式下花费的 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))
您可以使用psutil.Popen 启动一个子进程,并在子进程运行时以可移植的方式获取附加信息(cpu、内存、网络连接、线程、fds、子进程等)。
另请参阅,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())
或者使用带有命名管道的-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)