我正在处理一个将在命令行中运行的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)我怎样才能做到这一点?此外,如果有一个比使用‘时间’更好的方法,我是开放的尝试。
发布于 2022-03-17 00:03:51
为了提供当前的壁时间,可以将time.time()用于得到划时代的时间。
为了提供经过的墙壁时间,可以在操作开始和结束时使用time.perf_counter(),结果的差异反映了运行时间。如其他答案所述,不能将结果用于给出参照点未定义。的绝对时间,您可以使用timeit.default_time()但使用截至python 3.3
为了提供经过的CPU时间,time.process_time()可以以类似于time.perf_counter()的方式使用。这将是提供系统和用户CPU时间的总和。
https://stackoverflow.com/questions/56672370
复制相似问题