让你Python到很爽的加速递归函数的装饰器
今天我们会讲到一个[装饰器]
注记:链接“装饰器”指Python3教程中的装饰器教程。可以在这里快速了解什么是装饰器。
@functools.lru_cache——进行函数执行结果备忘,显著提升递归函数执行时间。
示例:寻找宝藏。在一个嵌套元组tuple或列表list中寻找元素'GoldCoin'
importtime fromfunctoolsimportlru_cache deffind_treasure(box): foriteminbox: ifisinstance(item,(tuple,list)): find_treasure(item) elifitem=='GoldCoin': print('Findthetreasure!') returnTrue start=time.perf_counter() find_treasure(('sth','sth','sth', ('BadCoin','normalcoin','fish','sth','anysth'), ('BadCoin','normalcoin','fish','sth','anysth'), 'GoldCoin',)) end=time.perf_counter() run_time_without_cache=end-start print('在没有Cache的情况下,运行花费了{}s。'.format(run_time_without_cache)) @lru_cache() deffind_treasure_quickly(box): foriteminbox: ifisinstance(item,(tuple,list)): find_treasure(item) elifitem=='GoldCoin': print('Findthetreasure!') returnTrue start=time.perf_counter() find_treasure_quickly(('sth','sth','sth', ('BadCoin','normalcoin','fish','sth','anysth'), ('BadCoin','normalcoin','fish','sth','anysth'), 'GoldCoin',)) 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)))
最终输出
Findthetreasure!
在没有Cache的情况下,运行花费了0.0002182829999810565s。
Findthetreasure!
在有Cache的情况下,运行花费了0.00011638000000857573s。
有Cache比没Cache快0.00010190299997248076s。
注记:运行这个示例时我的电脑配置如下
CPU:AMDRyzen52600 RAM:KingstonHyperX8Gigabytes2666
约使用7个月。
这个装饰器可以在函数运行时记录它的输入值与运行结果。当元组('BadCoin','normalcoin','fish','sth','anysth')出现第二次时,加了这个装饰器的函数find_the_treasure_quickly不会再次在递归时对这个元组进行查找,而是直接在“备忘录”中找到运行结果并返回!
总结
以上所述是小编给大家介绍的让你Python到很爽的加速递归函数的装饰器,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对毛票票网站的支持!