获取Python2.7中代码块的执行时间

2024-03-28 23:40:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我想测量在Python程序中计算代码块所用的时间, 可能在用户cpu时间、系统cpu时间和运行时间之间分离。

我知道timeit模块,但我有许多自己编写的函数,这并不容易 在安装过程中传递它们。

我宁愿要一些可以用的东西,比如:

#up to here I have done something....
start_counting() #or whatever command used to mark that I want to measure
                   #the time elapsed in the next rows
# code I want to evaluate
user,system,elapsed = stop_counting() #or whatever command says:
                                      #stop the timer and return the times

用户和系统CPU时间不是必需的(尽管我想测量它们), 但在过去的一段时间里,我希望能够做这样的事情, 而不是使用复杂的命令或模块。


Tags: 模块ortheto用户程序系统时间
3条回答

要以秒为单位获取经过的时间,可以使用^{}

import timeit
start_time = timeit.default_timer()
# code you want to evaluate
elapsed = timeit.default_timer() - start_time

使用timeit.default_timer()而不是time.time()time.clock(),因为它将为任何平台选择具有更高分辨率的计时函数。

我发现自己一次又一次地解决这个问题,所以我最终为它创建了一个library。用pip install timer_cm安装。然后:

from time import sleep
from timer_cm import Timer

with Timer('Long task') as timer:
    with timer.child('First step'):
        sleep(1)
    for _ in range(5):
        with timer.child('Baby steps'):
            sleep(.5)

输出:

Long task: 3.520s
  Baby steps: 2.518s (71%)
  First step: 1.001s (28%)

我总是使用decorator为现有函数做一些额外的工作,包括获取执行时间。这是Python和简单。

import time

def time_usage(func):
    def wrapper(*args, **kwargs):
        beg_ts = time.time()
        retval = func(*args, **kwargs)
        end_ts = time.time()
        print("elapsed time: %f" % (end_ts - beg_ts))
        return retval
    return wrapper

@time_usage
def test():
    for i in xrange(0, 10000):
        pass

if __name__ == "__main__":
    test()

相关问题 更多 >