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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值