Python函数修饰器之二

2019-02-28  本文已影响0人  louyang
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

上一篇下一篇

猜你喜欢

热点阅读