1. 應用場景:算法
屢次調用同一函數緩存
2. 普通寫法:函數
1 def say(name): 2 print("hellow:%s"%name) 3 now = datetime.datetime.now() 4 return now 5 6 now = say('tom') 7 print("time:%s"%now) 8 time.sleep(5) 9 10 now = say('tom') 11 print("time:%s"%now)
結果:spa
hellow:tom
time:2019-09-05 18:20:19.637917
hellow:tom
time:2019-09-05 18:20:24.639228code
3. 緩存寫法:blog
1 import time 2 import datetime 3 from functools import lru_cache 4 5 @lru_cache(maxsize=32) 6 def say(name): 7 print("hellow:%s"%name) 8 now = datetime.datetime.now() 9 return now 10 11 now = say('tom') 12 print("time:%s"%now) 13 time.sleep(5) 14 15 now = say('tom') 16 print("time:%s"%now)
結果:hash
hellow:tom
time:2019-09-05 16:30:22.451122
time:2019-09-05 16:30:22.451122class
4. 總結:import
lru_cache(maxsize=128,typed=False)
接收兩個參數,第一個參數 maxsize
表示最多緩存多少個結果,這個數字建議設置爲2的冪。超出這個結果就會啓用 LRU 算法刪除不經常使用的數據。第二個參數 typed
表示是否檢查參數類型,默認爲 False
,若是設置爲 True
,那麼參數 3
和 3.0
會被當作不一樣的數據處理。lru_cache
底層是基於字典來實現的緩存,因此參數都必須是 hashable 的,不然會致使報錯。它山之石——未聞codedate