
记忆化是一种优化技术,用于通过存储昂贵的函数调用的结果并在再次出现相同的输入时重用它们来加速程序。在 Python 中,functools 模块提供了 lru_cache 装饰器,它提供了一种缓存函数结果的简单方法。在函数调用的计算成本较高且使用相同的参数重复调用函数的情况下,此方法特别有用。
什么是lru_cache?functools 模块中的 lru_cache (Least Recently Used cache) 装饰器缓存函数的结果,以便具有相同参数的后续调用可以返回缓存的结果,而不是重新计算它。这可以显著提高性能,尤其是对于递归函数或计算成本高昂的函数。
lru_cache 的基本用法要使用 lru_cache,您只需用 @lru_cache 修饰函数即可。下面是一个基本示例:
from functools import lru_cache@lru_cache(maxsize=None)def expensive_function(n): # Simulate an expensive computation print(f"Computing expensive_function({n})") return n * n# Call the function with the same argument multiple timesprint(expensive_function(4)) # Output: Computing expensive_function(4) 16print(expensive_function(4)) # Output: 16 (result is cached, no computation)在此示例中,使用参数 4 调用 expensive_function 两次。第一次调用计算结果,而第二次调用从缓存中检索结果,从而避免计算。
lru_cache 参数maxsize:指定最大缓存调用数。当高速缓存已满时,将丢弃最近使用最少的条目。将 maxsize 设置为 None 意味着缓存可以无限增长。typed:如果设置为 True,则不同类型的参数将单独缓存。例如,f(3) 和 f(3.0) 将被视为不同的调用。记忆化的实际示例:斐波那契数列斐波那契数列是一个典型的例子,其中记忆化可以显着提高性能。如果没有记忆化,朴素的递归方法具有指数级的时间复杂性。使用 lru_cache,我们可以将其优化为线性时间复杂度。
from functools import lru_cache@lru_cache(maxsize=None)def fibonacci(n): if n < 2: return n return fibonacci(n - 1) + fibonacci(n - 2)# Compute Fibonacci numbersprint(fibonacci(10)) # Output: 55print(fibonacci(50)) # Output: 12586269025在此示例中,fibonacci 函数通过缓存每次计算的结果来有效地计算 Fibonacci 数列。
将lru_cache与关键字参数一起使用lru_cache 还可以处理带有关键字参数的函数。下面是一个示例:
from functools import lru_cache@lru_cache(maxsize=None)def greet(name, greeting="Hello"): print(f"Generating greeting for {name}") return f"{greeting}, {name}!"# Call the function with the same argumentsprint(greet("Alice")) # Output: Generating greeting for Alice Hello, Alice!print(greet("Alice")) # Output: Hello, Alice! (result is takan from the cache)print(greet("Alice", greeting="Hi")) # Output: Generating greeting for Alice Hi, Alice!print(greet("Alice", greeting="Hi")) # Output: Hi, Alice! (result is takan from the cache)如果使用相同的参数调用函数,则结果将从缓存中获取
清除缓存有时,您可能希望清除缓存,例如,如果缓存的数据变得无效,或者您想要对更新的数据运行代码。您可以使用 cache_clear 方法执行此操作:
# Clear the cachefibonacci.cache_clear()functools 模块中的 lru_cache 装饰器是 Python 中记忆化的强大工具。通过缓存昂贵的函数调用的结果,lru_cache可以显著提高程序的性能。它在递归算法和使用相同的参数重复调用函数的方案中特别有用