📜  Python Functools – lru_cache()

📅  最后修改于: 2022-05-13 01:55:45.708000             🧑  作者: Mango

Python Functools – lru_cache()

Python中的functools模块处理高阶函数,即操作(作为参数)或返回函数和其他此类可调用对象的函数。 functools 模块提供了大量的方法,例如cached_property(func), cmp_to_key(func), lru_cache(func), wraps(func),等。值得注意的是,这些方法以函数作为参数。

lru_cache()

lru_cache()functools模块中的一个这样的函数,它通过使用记忆技术帮助减少函数的执行时间。

示例:1

from functools import lru_cache
import time
  
  
# Function that computes Fibonacci 
# numbers without lru_cache
def fib_without_cache(n):
    if n < 2:
        return n
    return fib_without_cache(n-1) + fib_without_cache(n-2)
      
# Execution start time
begin = time.time()
fib_without_cache(30)
  
# Execution end time
end = time.time()
  
print("Time taken to execute the\
function without lru_cache is", end-begin)
  
# Function that computes Fibonacci
# numbers with lru_cache
@lru_cache(maxsize = 128)
def fib_with_cache(n):
    if n < 2:
        return n
    return fib_with_cache(n-1) + fib_with_cache(n-2)
      
begin = time.time()
fib_with_cache(30)
end = time.time()
  
print("Time taken to execute the \
function with lru_cache is", end-begin)

输出:

示例 2:

from functools import lru_cache
  
@lru_cache(maxsize = 100)
def count_vowels(sentence):
    sentence = sentence.casefold()
    return sum(sentence.count(vowel) for vowel in 'aeiou')
      
print(count_vowels("Welcome to Geeksforgeeks"))

输出:

9