• 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
  • 相关阅读:
    seajs模块化开发
    agularJs 路由
    sass
    web工作流
    lufylegend游戏引擎
    canvas游戏之贪食蛇
    [bzoj3743 Coci2015] Kamp(树形dp)
    [bzoj2662 BeiJing wc2012] 冻结 (分层图+最短路)
    [luogu2680] 运输计划 (lca+二分+树上差分)
    [luogu1463 HAOI2007] 反素数 (约数)
  • 原文地址:https://www.cnblogs.com/cymwill/p/8876612.html
Copyright © 2020-2023  润新知