%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)



