The functools
module in Python is used to create 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.
cache
decoratorcache
is a decorator that helps in reducing function execution for the same inputs using the memoization technique. The function returns the same value as lru_cache(maxsize=None)
, where the cache grows indefinitely without evicting old values. The decorator creates a thin wrapper around a dictionary lookup for the function arguments.
@cache
The decorator has no parameters.
This code example below measures and compares the execution times of calculating the Fibonacci sequence with and without using the cache decorator, showcasing the performance improvement achieved through caching.
Let’s look at the code below:
from functools import cacheimport time@cachedef fibonacci(n):if n <= 1:return nelse:return fibonacci(n-1) + fibonacci(n-2)start_time = time.time()fibonacci(40)end_time = time.time()execution_time_without_cache = end_time - start_timeprint("Time taken without cache: {:.8f} seconds".format(execution_time_without_cache))start_time = time.time()fibonacci(40)end_time = time.time()execution_time_with_cache = end_time - start_timeprint("Time taken with cache: {:.8f} seconds".format(execution_time_with_cache))
Lines 1 and 2: This imports the cache
decorator from the functools
module and the time
module, which will be used for measuring execution time.
Lines 4 and 9: This defines the fibonacci
function, which calculates the Fibonacci sequence. The function is decorated with @cache
, enabling caching to improve performance by storing previously computed values.
Lines 11–13: This captures the starting time using time.time()
before invoking the fibonacci
function with an input value of 40. The function is called to calculate the Fibonacci sequence.
Line 14: This calculates the execution time by subtracting the start_time
from the end_time
. The result is stored in the variable execution_time_without_cache
.
Line 15: This prints the execution time without cache, formatted to display the value of execution_time_without_cache
with six decimal places.
Lines 17–19: This updates the start_time
with the current time again.
Line 20: This calculates the execution time for the Fibonacci calculation with the cache enabled by subtracting the start_time
from the end_time
. The result is stored in the variable execution_time_with_cache
.
Line 21: This prints the execution time with cache, formatted to display the value of execution_time_with_cache
with six decimal places.
The output of the code indicates that the running time of the fibonacci
method with the cache is better than the fibonacci
method without the cache.
Free Resources