Python3.7.3 # Python>=3.2
I usually hear that redis is used for caching, but redis changes the cache to store the result data. Starting from version 3.2 of Python, a very elegant caching machine has been introduced
from functools import lru_cache
lru_cache can improve the efficiency of program execution, especially suitable for time-consuming functions. You only need to add decorators to the required functions to achieve the effect of caching, especially some recursive functions
def fab(n):if n <=2:return n
returnfab(n-1)+fab(n-2)print(datetime.datetime.now()) # 2019-05-2414:21:43fab(40)print(datetime.datetime.now()) # 2019-05-2414:22:20
When the cache is not used, the running time of fab(40) takes about 37 seconds??
from functools import lru_cache
import datetime
@ lru_cache(None)
def fab(n):if n <=2:return n
returnfab(n-1)+fab(n-2)print(datetime.datetime.now()) # 2019-05-2414:24:00.229715fab(40)print(datetime.datetime.now()) # 2019-05-2414:24:00.229823
When the cache is added, it takes less than 1 second to execute fab(40)??
Do a little test
def fab(n):print(n)return None
fab(10)fab(10)fab(10)
from functools import lru_cache
@ lru_cache(None)
def fab(n):print(n)return None
fab(10)fab(10)fab(10)fab(9)fab(9)
**It can be seen from the result that when fab(10) is called the second time, the function body is not actually executed, but the cached result is directly returned. **
**Using the lur_cache decorator of the functools module can cache up to maxsize call results of this function, thereby improving the efficiency of program execution, especially suitable for time-consuming functions. The parameter maxsize is the maximum number of caches. If it is None, there is no limit. When set to 2n, the performance is the best; if typed=True (note that there is no such parameter in functools32), calls of different parameter types will be cached separately. For example, f(3) and f(3.0). **** The function decorated by lru_cache has two methods, cache_clear and cache_info, which are used to clear the cache and view cache information respectively. **
Recommended Posts