The functools module in Python creates higher-order functions that interact with other functions. The higher-order functions either return other functions or operate on them to broaden the function’s scope without modifying or explicitly defining them.
lru_cache()
Memoization is a caching technique that ensures a function need not run multiple times for the same inputs. Instead, the result of the function is stored in memory the first time it’s run and can be referenced later when necessary.
Note: Refer to What is memoization? to learn more about memoization.
lru_cache()
is a decorator that helps in reducing function execution for the same inputs using the memoization technique.
The wrapped method has a cache_info()
function that produces a named tuple containing hits
, misses
, maxsize
, and currsize
to assess the cache’s efficacy and optimize the maxsize
parameter.
@lru_cache(maxsize=<max_size>, typed=True/False)
The decorator has two parameters:
maxsize
: This parameter indicates the maximum number of entries the cache can store before evicting old items. If it’s set to none, the cache will grow indefinitely, and no entries will ever be evicted. This will lead to problems if many entries are cached.
typed
: This is a Boolean parameter. When set to True
, it indicates the cache will have different entries for different types of function arguments.
from functools import lru_cacheimport timedef fibonacci_without_cache(num):if num < 2: return numreturn fibonacci_without_cache(num - 1) + fibonacci_without_cache(num - 2)@lru_cache(maxsize=12)def fibonacci_with_cache(num):if num < 2: return numreturn fibonacci_without_cache(num - 1) + fibonacci_without_cache(num - 2)start_timer = time.time()print("fibonacci_without_cache(8):", fibonacci_without_cache(8))end_timer = time.time()print("Time taken to calculate fibonacci series without cache:", end_timer - start_timer)start_timer = time.time()print("fibonacci_with_cache(8):", fibonacci_with_cache(8))end_timer = time.time()print("Time taken to calculate fibonacci series with cache:", end_timer - start_timer)print("Cache information of fibonacci_with_cache function:\n",fibonacci_with_cache.cache_info())
lru_cache
decorator and time module.fibonacci_without_cache
.fibonacci_with_cache
. This method is decorated with @lru_cache
with the max cache size as 12
.fibonacci_without_cache()
method with the help of the time
module.fibonacci_with_cache()
method with the help of the time
module.cache_info()
method to obtain the cache information for fibonacci_with_cache()
.