python中的效能優化的裝飾器
阿新 • • 發佈:2021-01-20
技術標籤:python
-
LRU lru_cache Least Recently Used 是快取置換中的一種常用演算法,從原始碼中看
-
If maxsize is set to None, the LRU features are disabled and the cache
can grow without bound. -
If typed is True, arguments of different types will be cached separately.
For example, f(3.0) and f(3) will be treated as distinct calls with- 該裝飾器有兩個引數,一個是可以快取的最大次數maxsize,
- 一個是typed ,如果該引數是True,不同型別的引數分別快取。如果為False,之快取一次。
- 這個裝飾可以用來優化遞迴演算法,效能很明顯。
- 程式碼如下:
from timeit import Timer from functools import lru_cache import sys sys.setrecursionlimit(2000) # 設定最大遞迴深度 @lru_cache(128) # 128 快取的最大次數,如果沒有,為無窮大 def fibo(n): if n == 1 or n ==
-
使用 Timer 來計算程式碼執行的時間,計算斐波那契數列的前20項和。
-
不適用快取裝飾器的話耗時:
-
耗時6秒,而且計算前50項的時候,我的電腦已經計算不出來。
-
而使用快取裝飾用時如圖:
-
相差了將近1000倍。
-
而且可以計算斐波那契數列的前1000項和的值
-
耗時0.9s ,效能提升有很明顯的優勢