python测试函数的使用时间

1. 使用装饰器来衡量函数执行时间

有一个简单方法,那就是定义一个装饰器来测量函数的执行时间,并输出结果:(代码通用3.x)

import time
from functools import wraps

def fn_timer(function):
     @wraps(function)
     def function_timer(*args, **kwargs):
         t0 = time.time()
         result = function(*args, **kwargs)
         t1 = time.time()
         print("Total time running %s: %s seconds" %
             (function.__name__, str(t1-t0))
             )
         return result
     return function_timer

要测试函数的使用时间时,只需要@fn_timer装饰器即可。

@fn_timer
def myfunction(...):
...

下面是测试:

In [14]: @fn_timer
    ...: def norm(a):
    ...:     return sum(a**2)**(1/2)
    ...:

In [15]: @fn_timer
    ...: def norm2(a):
    ...:     return la.norm(a)
    ...:

In [16]: norm(a)
Total time running norm: 0.0 seconds
Out[16]: 4.7958315233127191

In [17]: norm2(a)
Total time running norm2: 0.0 seconds
Out[17]: 4.7958315233127191

In [18]: a = np.random.randint(-3,3,(10000,))

In [19]: norm(a)
Total time running norm: 0.0010035037994384766 seconds
Out[19]: 177.92695130305583

In [20]: norm2(a)
Total time running norm2: 0.001010894775390625 seconds
Out[20]: 177.92695130305583

In [21]: a = np.random.randint(-3,3,(50000,))

In [22]: norm(a)
Total time running norm: 0.005008220672607422 seconds
Out[22]: 397.39275282772837

In [23]: norm2(a)
Total time running norm2: 0.0 seconds
Out[23]: 397.39275282772837
原文地址:https://www.cnblogs.com/cymwill/p/8876612.html