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

作者:咖京学习 时间:2022-10-23 13:04:47 

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

注记:链接“装饰器”指Python3教程中的装饰器教程。可以在这里快速了解什么是装饰器。

@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个月。

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

总结

以上所述是小编给大家介绍的让你Python到很爽的加速递归函数的装饰器网站的支持!

来源:https://www.jianshu.com/p/66e1fe314154

标签:python,递归函数,装饰器
0
投稿

猜你喜欢

  • 淘宝网获亚洲最佳在线客户体验大奖

    2009-03-31 12:55:00
  • MySQL数据库性能优化之索引优化

    2012-05-08 07:16:37
  • tensorflow 变长序列存储实例

    2023-08-28 01:05:40
  • 浅谈python opencv对图像颜色通道进行加减操作溢出

    2021-12-26 11:45:23
  • Golang拾遗之自定义类型和方法集详解

    2024-03-19 03:08:29
  • 理解python中生成器用法

    2022-08-27 10:49:59
  • 用户如何有效地利用ORACLE数据字典

    2008-03-04 18:19:00
  • PHP 中文简繁互转代码 完美支持大陆、香港、台湾及新加坡

    2023-11-15 11:46:16
  • python制作抽奖程序代码详解

    2022-05-04 08:51:18
  • Asp操作Xml的精炼类,含示例代码

    2011-02-28 11:11:00
  • JavaScript判断微信浏览器实例代码

    2024-04-18 09:30:31
  • python3 logging日志封装实例

    2022-05-23 08:27:52
  • Viso 2019 下载与激活方法

    2023-03-19 08:17:44
  • SQL Server序列SEQUENCE用法介绍

    2024-01-21 02:43:21
  • MySQL创建数据库并支持中文字符的操作方法

    2024-01-27 16:09:45
  • 10个最容易犯的HTML标签错误

    2010-09-13 12:37:00
  • pytorch获取模型某一层参数名及参数值方式

    2022-07-03 06:10:28
  • asp组件上传

    2010-05-27 12:16:00
  • 利用XML实现通用WEB报表打印实际使用中的例子

    2008-09-04 14:42:00
  • 快速修复损坏的MySQL数据库

    2024-01-20 07:38:42
  • asp之家 网络编程 m.aspxhome.com