gpt4 book ai didi

python-3.x - 如何使用内置 bash 'time' 在 Python 变量中捕获挂钟时间和 CPU 时间?

转载 作者:行者123 更新时间:2023-12-03 18:21:27 25 4
gpt4 key购买 nike

我正在编写一个将在命令行中运行的 Python 脚本。这个想法是从用户那里得到一个命令,运行它,然后提供用户提供的命令的挂钟时间和 CPU 时间。请参阅下面的代码。

#!/usr/bin/env python 
import os
import sys

def execut_cmd(cmd_line):
utime = os.system('time '+cmd_line)
# Here I would like to store the wall-clock time in the Python variable
# utime.
cputime = os.system('time '+cmd_line)
# Here the CPU time in the cputime variable. utime and cputime are going to
# be used later in my Python script. In addition, I would like to silence the
# output of time in the screen.

execut_cmd(sys.argv[1])
print ('Your command wall-clock time is '+utime)
print ('Your command cpu time is '+ cputime)

我怎样才能做到这一点?此外,如果有比使用“时间”更好的方法,我愿意尝试。

最佳答案

要提供当前的挂钟时间,time.time()可用于get the epoch time.
要提供经过的挂墙时间,time.perf_counter()可以在操作的开始和结束时使用,结果的差异反射(reflect)了耗时。结果不能用于给出绝对时间 the reference point is undefined.如其他答案所述,您可以使用 timeit.default_time()但是 this will always return time.perf_counter() as of python 3.3
要提供经过的 CPU 时间,time.process_time()可以以与 time.perf_counter() 类似的方式使用.这将provide the sum of the system and user CPU time.

关于python-3.x - 如何使用内置 bash 'time' 在 Python 变量中捕获挂钟时间和 CPU 时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56672370/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com