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

 

相关文章:

  • 2022-03-06
  • 2022-12-23
  • 2021-09-25
  • 2022-12-23
  • 2021-06-20
  • 2021-10-16
  • 2021-11-15
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2021-07-29
  • 2022-12-23
  • 2022-12-23
  • 2021-12-05
  • 2021-11-17
  • 2022-12-23
相关资源
相似解决方案