| by Arround The Web | No comments

Python Functools Lru_Cache

In Python, the “functools” module provides/gives higher-order functions that can take or retrieve different functions as arguments. Some of the functions in this module are “wraps(func), lru_cache(func), cmp_to_key(func), and cached_property(func). The functools module also supports memoization, which is a technique to improve performance by caching the results of function calls.

Python’s “lru_cache()” decorator is a tool from the standard library that uses memoization to speed up function execution. This article will present the following contents:

What is the “lru_cache()” in Python?

The “lru_cache()” is a function decorator that can be utilized to cache the output of a function call using the Least Recently Used (LRU) strategy. Cache memory stores the most recent or frequently used results for faster access and discards the oldest or least used results when it is full.

Syntax

@lru_cache(maxsize=128, typed=False)

The lru_cache() decorator takes two optional arguments:

  • maxsize: This parameter indicates the maximum size of the cache. If the cache is at full/maximum size, the not-utilized results will be evicted. The default value is 128.
  • typed: This parameter indicates the Boolean value that indicates whether the cache should be typed. If “typed” is True, then different types of function arguments will be cached separately.

Example 1: Using “lru_cache()” to Speed Up the Computation

The cache keeps the most current inputs/results pair and removes the least recent/oldest ones when it is full. This helps us print the Fibonacci sequence faster. The Fibonacci sequence is a series where every individual number is the addition of the last/previous two numbers.

We can use the “lru_cache” to speed up the computation of the Fibonacci sequence. We can also use time to compare how long the function takes with and without the “lru_cache”. Here is a code:

from functools import lru_cache
import time

# Recursive Fibonacci calculation without cache
def fib_nc(n):
  if n < 4:
    return n
  return fib_nc(n - 1) + fib_nc(n - 4)

begin = time.time()
fib_nc(60)
end = time.time()
print("Time w/o cache:", end - begin)
# Fibonacci calculation with cache using lru_cache
@lru_cache(maxsize=128)
def fib_wc(n):
  if n < 4:
    return n
  return fib_wc(n - 1) + fib_wc(n - 2)

begin = time.time()
fib_wc(60)
end = time.time()
print("Time with cache:", end - begin)

In this code:

  • We imported the “time” module and “lru_cache” from the Python “functools” module.
  • We defined a function called “fib_nc” to compute the Fibonacci series without using the “lru_cache”.
  • Next, the variable “begin” is created to store the starting time and passed to the “fib_nc” function.
  • After that, the variable “end” is created to store the ending time.
  • Next, the time taken to print the Fibonacci series without using the “lru_cache” is printed.
  • Next, we used the “lru_cache” function by setting the “max_size” value for the “lru_cache” function.
  • We decorated the “fib_wc” function with the lru_cache to make the computation of the Fibonacci series faster.
  • The function used the same formula as discussed in previous steps.
  • Finally, we measured the time execution with the “begin” and “end” variables and printed them to the console.

Output

The output shows the difference between using and not using the lru_cache decorator for the Fibonacci series.

Example 2: Utilizing the “lru_cache()” to Count the String Vowel

The below code uses the “lru_cache()” function decorator to determine the vowel in the specified string:

from functools import lru_cache
@lru_cache(maxsize = 60)
def vowels(str):
    str = str.casefold()
    return sum(str.count(i) for i in 'aeiou')
print(vowels("Welcome to Python Guide!"))

Here in this code:

  • The “lru_cache” is imported from the “functools”.
  • The “lru_cahe()” decorator takes the maxsize as an argument and sets its value to “60”.
  • After that, a function named “vowels” is defined with “string” as an input.
  • Inside the function, the “casefold()” method is used to transform the specified characters to lowercase.
  • Next, the “return” command is used to retrieve the vowel sum determined in the string.
  • Finally, the function is called on the specified string and retrieves the sum of vowels.

Output

The above output displays the sum of the string vowels.

Conclusion

In Python, the “lru_cache()” function decorator of the “functools” module is used to reduce the function time execution by utilizing the memorization process. This function decorator is used to speed up the computation process, such as while determining the Fibonacci series or finding the vowels from the string. This blog presented/delivered an in-depth guide on Python “lru_cache()” using numerous examples.

Share Button

Source: linuxhint.com

Leave a Reply