我有一个Python命令行程序,需要一段时间才能完成。我想知道完成跑步所需的确切时间。

我看过timeit模块,但它似乎只适用于小代码片段。我想给整个节目计时。


当前回答

使用line_profiler。

line_profiler将描述单个代码行执行所需的时间。分析器通过Cython在C语言中实现,以减少分析开销。

from line_profiler import LineProfiler
import random

def do_stuff(numbers):
    s = sum(numbers)
    l = [numbers[i]/43 for i in range(len(numbers))]
    m = ['hello'+str(numbers[i]) for i in range(len(numbers))]

numbers = [random.randint(1,100) for i in range(1000)]
lp = LineProfiler()
lp_wrapper = lp(do_stuff)
lp_wrapper(numbers)
lp.print_stats()

结果将是:

Timer unit: 1e-06 s

Total time: 0.000649 s
File: <ipython-input-2-2e060b054fea>
Function: do_stuff at line 4

Line #      Hits         Time  Per Hit   % Time  Line Contents
==============================================================
     4                                           def do_stuff(numbers):
     5         1           10     10.0      1.5      s = sum(numbers)
     6         1          186    186.0     28.7      l = [numbers[i]/43 for i in range(len(numbers))]
     7         1          453    453.0     69.8      m = ['hello'+str(numbers[i]) for i in range(len(numbers))]

其他回答

以下代码段以可读的<HH:MM:SS>格式打印经过的时间。

import time
from datetime import timedelta

start_time = time.time()

#
# Perform lots of computations.
#

elapsed_time_secs = time.time() - start_time

msg = "Execution took: %s secs (Wall clock time)" % timedelta(seconds=round(elapsed_time_secs))

print(msg)    

首先,以管理员身份打开命令提示符(CMD)并在那里键入,安装人性化的软件包-pip安装人性化

代码:

from humanfriendly import format_timespan
import time
begin_time = time.time()
# Put your code here
end_time = time.time() - begin_time
print("Total execution time: ", format_timespan(end_time))

输出:

我使用来自ttictoc的tic和toc。

pip install ttictoc

然后可以在脚本中使用:

from ttictoc import tic,toc
tic()

# foo()

print(toc())

time.clock在Python 3.3中已被弃用,并将从Python 3.8中删除:请改用time.perf_counter或time.prrocess_time

import time
start_time = time.perf_counter ()
for x in range(1, 100):
    print(x)
end_time = time.perf_counter ()
print(end_time - start_time, "seconds")

我将这个timing.py模块放入我自己的站点包目录中,并在模块顶部插入导入计时:

import atexit
from time import clock

def secondsToStr(t):
    return "%d:%02d:%02d.%03d" % \
        reduce(lambda ll,b : divmod(ll[0],b) + ll[1:],
            [(t*1000,),1000,60,60])

line = "="*40
def log(s, elapsed=None):
    print line
    print secondsToStr(clock()), '-', s
    if elapsed:
        print "Elapsed time:", elapsed
    print line
    print

def endlog():
    end = clock()
    elapsed = end-start
    log("End Program", secondsToStr(elapsed))

def now():
    return secondsToStr(clock())

start = clock()
atexit.register(endlog)
log("Start Program")

如果程序中有重要的阶段,我也可以在程序中调用timing.log。但仅包括导入计时就可以打印开始和结束时间,以及总运行时间。(请原谅我晦涩难懂的secondsToStr函数,它只是将浮点秒数设置为hh:mm:ss.sss格式。)

注意:上述代码的Python3版本可以在这里找到。