让你Python到很爽的加速递归函数的装饰器!

Python技巧——好用的一个装饰器

今天我们会讲到一个[ 装饰器 ]

@functools.lru_cache ——进行函数执行结果备忘,显著提升递归函数执行时间。

示例:寻找宝藏。在一个嵌套元组 tuple 或列表 list 中寻找元素 'Gold Coin'

import time
from functools import lru_cache
def find_treasure(box):
for item in box:
if isinstance(item, (tuple, list)):
find_treasure(item)
elif item == 'Gold Coin':
print('Find the treasure!')
return True
start = time.perf_counter()
find_treasure(('sth', 'sth', 'sth',
('Bad Coin', 'normal coin', 'fish', 'sth', 'any sth'),
('Bad Coin', 'normal coin', 'fish', 'sth', 'any sth'),
'Gold Coin', ))
end = time.perf_counter()
run_time_without_cache = end - start
print('在没有Cache的情况下,运行花费了{} s。'.format(run_time_without_cache))
@lru_cache()
def find_treasure_quickly(box):
for item in box:
if isinstance(item, (tuple, list)):
find_treasure(item)
elif item == 'Gold Coin':
print('Find the treasure!')
return True
start = time.perf_counter()
find_treasure_quickly(('sth', 'sth', 'sth',
('Bad Coin', 'normal coin', 'fish', 'sth', 'any sth'),
('Bad Coin', 'normal coin', 'fish', 'sth', 'any sth'),
'Gold Coin', ))
end = time.perf_counter()
run_time_with_cache = end - start
print('在有Cache的情况下,运行花费了{} s。'.format(run_time_with_cache))
print('有Cache比没Cache快{} s。'.format(float(run_time_without_cache-run_time_with_cache)))
最终输出

Find the treasure!
在没有Cache的情况下,运行花费了0.0002182829999810565 s。
Find the treasure!
在有Cache的情况下,运行花费了0.00011638000000857573 s。
有Cache比没Cache快0.00010190299997248076 s。
注记: 运行这个示例时我的电脑配置如下

CPU:AMD Ryzen 5 2600

RAM:Kingston HyperX 8Gigabytes 2666

约 使用7个月 。Python学习交流群:1004391443,这里有资源共享,技术解答,还有小编从最基础的Python资料到项目实战的学习资料都有整理,希望能帮助你更了解python,学习python

这个装饰器可以 在函数运行时记录它的输入值与运行结果 。当元组 ('Bad Coin', 'normal coin', 'fish', 'sth', 'any sth') 出现第二次时,加了这个装饰器的函数 find_the_treasure_quickly 不会再次在递归时对这个元组进行查找,而是 直接在“备忘录”中找到运行结果并返回 !

猜你喜欢

转载自blog.csdn.net/weixin_34408624/article/details/90923042