性能篇——函數調用結果的 LRU 緩存

 

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 算法規則:最近最常使用的參數生成的結果,咱們存下來,下次遇到相同的參數時直接返回結果。而不常出現的參數,等到須要的時候再計算。計算完成後,也先存下來。可是若是緩存空間不夠了,不常使用的會先刪除。
  • lru_cache(maxsize=128,typed=False)接收兩個參數,第一個參數 maxsize表示最多緩存多少個結果,這個數字建議設置爲2的冪。超出這個結果就會啓用 LRU 算法刪除不經常使用的數據。第二個參數 typed表示是否檢查參數類型,默認爲 False,若是設置爲 True,那麼參數 33.0會被當作不一樣的數據處理。
  • 因爲 lru_cache底層是基於字典來實現的緩存,因此參數都必須是 hashable 的,不然會致使報錯。

它山之石——未聞codedate

相關文章
相關標籤/搜索