讓你Python到很爽的加速遞歸函數(shù)的裝飾器
今天我們會講到一個[裝飾器]
注記:鏈接“裝飾器”指Python3教程中的裝飾器教程。可以在這里快速了解什么是裝飾器。
@functools.lru_cache——進(jìn)行函數(shù)執(zhí)行結(jié)果備忘,顯著提升遞歸函數(shù)執(zhí)行時間。
示例:尋找寶藏。在一個嵌套元組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的情況下,運(yùn)行花費(fèi)了{(lán)} 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的情況下,運(yùn)行花費(fèi)了{(lán)} s。'.format(run_time_with_cache))
print('有Cache比沒Cache快{} s。'.format(float(run_time_without_cache-run_time_with_cache)))
最終輸出
Find the treasure!
在沒有Cache的情況下,運(yùn)行花費(fèi)了0.0002182829999810565 s。
Find the treasure!
在有Cache的情況下,運(yùn)行花費(fèi)了0.00011638000000857573 s。
有Cache比沒Cache快0.00010190299997248076 s。
注記:運(yùn)行這個示例時我的電腦配置如下
CPU:AMD Ryzen 5 2600 RAM:Kingston HyperX 8Gigabytes 2666
約使用7個月。
這個裝飾器可以在函數(shù)運(yùn)行時記錄它的輸入值與運(yùn)行結(jié)果。當(dāng)元組('Bad Coin', 'normal coin', 'fish', 'sth', 'any sth')出現(xiàn)第二次時,加了這個裝飾器的函數(shù)find_the_treasure_quickly不會再次在遞歸時對這個元組進(jìn)行查找,而是直接在“備忘錄”中找到運(yùn)行結(jié)果并返回!
總結(jié)
以上所述是小編給大家介紹的讓你Python到很爽的加速遞歸函數(shù)的裝飾器,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復(fù)大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
- Python 中的函數(shù)裝飾器和閉包詳解
- Python高階函數(shù)與裝飾器函數(shù)的深入講解
- 如何實現(xiàn)一個python函數(shù)裝飾器(Decorator)
- Python如何創(chuàng)建裝飾器時保留函數(shù)元信息
- python裝飾器相當(dāng)于函數(shù)的調(diào)用方式
- python函數(shù)裝飾器之帶參數(shù)的函數(shù)和帶參數(shù)的裝飾器用法示例
- Python 裝飾器@,對函數(shù)進(jìn)行功能擴(kuò)展操作示例【開閉原則】
- Python函數(shù)裝飾器原理與用法詳解
- Python裝飾器限制函數(shù)運(yùn)行時間超時則退出執(zhí)行
- Python函數(shù)裝飾器的使用教程
相關(guān)文章
python使用Flask操作mysql實現(xiàn)登錄功能
這篇文章主要介紹了python使用Flask操作mysql實現(xiàn)登錄功能,代碼簡單易懂,非常不錯,具有一定的參考借鑒價值,需要的朋友可以參考下2018-05-05
詳談python read readline readlines的區(qū)別
下面小編就為大家?guī)硪黄斦刾ython read readline readlines的區(qū)別。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-09-09

