python装饰器实现耗时时间,第几次调用,以及缓存的功能

需求编写一个装饰器,用来装饰test函数

装饰器具有以下功能:

1、test调用时,可以打印是第几次调用  

2、test如果多次调用传入的参数相同,则第二次不需要耗时,直接返回结果,即实现简单缓存功能

3、test调用时,可以打印耗时时间

import time 



count = 0
cache = {}

def decorate(fn):
    

    def inner(*args, **kwargs):
        start = time.time()

        global count
        global cache
        if (args, str(kwargs)) in cache.keys():

            return cache[(args, str(kwargs))]
            data = fn(*args, **kwargs)
            cache[(args, str(kwargs))] = data  # 这里由于**kwargs是字典,而python字典的Key要是字符串类型,所以就str(kwargs)
            end = time.time()
            print("第%d次被调用" % (count) )
            print("耗时时间: ", end - start)
        return data
     return inner

@decorate
def test(word):
     time.sleep(2)
     return word.upper()


 if __name__ == '__main__':
     print(test("hero"))
     print(test("hero"))
    print(test("her"))

你可能感兴趣的:(python,开发语言)