美文网首页
Python函数修饰器之二

Python函数修饰器之二

作者: louyang | 来源:发表于2019-02-28 15:57 被阅读0次
    def calc_square(numbers):
        result = []
        for number in numbers:
            result.append(number*number)
        return result
    
    def calc_cube(numbers):
        result = []
        for number in numbers:
            result.append(number*number*number)
        return result
    
    array = range(1,100000)
    out_square = calc_square(array)
    out_cube = calc_cube(array)
    

    当我们面对上面这样的python程序,计算平方和立方各10万次。有的时候我们会希望测量这样的函数运行的时间。

    我们可以这样:

    import time
    
    def calc_square(numbers):
        start = time.time()
        result = []
        for number in numbers:
            result.append(number*number)
        end = time.time()
        print("calc_square took " + str(end-start) + " sec")
        return result
    
    def calc_cube(numbers):
        start = time.time()
        result = []
        for number in numbers:
            result.append(number*number*number)
        end = time.time()
        print("calc_cube took " + str(end-start) + " sec")
        return result
    
    array = range(1,100000)
    out_square = calc_square(array)
    out_cube = calc_cube(array)
    

    但是,当有更多函数需要加start/end的时候,我们就很难做了。一是代码尺寸大,修改的地方多;二是原有的代码被切割的支离破碎。

    用函数修饰器可以解决这个问题,所谓修饰器就是在不改变原有函数的基础上,增加新功能。

    import time
    
    def time_it(func):
        def wrapper(*args, **kwargs):
            start = time.time()
            result = func(*args, **kwargs)
            end = time.time()
            print(func.__name__ + " took " + str(end-start) + " sec")
            return result
        
        return wrapper
    
    @time_it
    def calc_square(numbers):
        result = []
        for number in numbers:
            result.append(number*number)
        return result
    
    @time_it
    def calc_cube(numbers):
        result = []
        for number in numbers:
            result.append(number*number*number)
        end = time.time()
    
    array = range(1,100000)
    out_square = calc_square(array)
    out_cube = calc_cube(array)
    

    运行结果:

    $ python a.py
    calc_square took 0.0116701126099 sec
    calc_cube took 0.0140378475189 sec
    
    参考

    https://www.youtube.com/watch?v=nYDKH9fvlBY

    相关文章

      网友评论

          本文标题:Python函数修饰器之二

          本文链接:https://www.haomeiwen.com/subject/kstkuqtx.html