简介:functools.lru_cache 是 Python 标准库中的一个非常实用的工具,它用于缓存函数的返回值,以提高程序性能。本文将介绍如何安装和使用 lru_cache,并通过函数式和面向对象的方式给出简单的示例。
历史攻略:
使用 lru_cache的好处:
1、提升性能:避免重复计算相同的结果。
2、简化代码:自动管理缓存,减少手动实现缓存逻辑的需要。
3、提高响应速度:提升函数调用的速度,特别是在涉及外部资源时。
4、节省资源:减少计算资源的使用,节省 CPU 和内存。
5、优化内存管理:通过 maxsize 参数控制缓存大小,优化内存使用。
案例源码:
# -*- coding: utf-8 -*-
# time: 2024/8/8 20:04
# file: lru_cache_demo.py
# author: tom
# 微信公众号: 玩转测试开发
from functools import lru_cache
# by function.
@lru_cache(maxsize=None)
def square(n):
print(f"Calculating square of {n}")
return n * n
@lru_cache(maxsize=10)
def add(x, y):
print(f"Adding {x} and {y}")
return x + y
@lru_cache(maxsize=5)
def repeat_string(s, times):
print(f"Repeating '{s}' {times} times")
return s * times
# by object.
class MathOperations:
@lru_cache(maxsize=None)
def square(self, n):
print(f"Calculating square of {n}")
return n * n
if __name__ == '__main__':
# by function.
print(square(4)) # 计算并缓存
print(square(4)) # 从缓存中获取结果
print(square(5)) # 计算并缓存
print(add(2, 3)) # 计算并缓存
print(add(2, 3)) # 从缓存中获取结果
print(add(3, 4)) # 计算并缓存
print(repeat_string("hello", 3)) # 计算并缓存
print(repeat_string("hello", 3)) # 从缓存中获取结果
print(repeat_string("world", 2)) # 计算并缓存
# by object.
mo = MathOperations()
print(mo.square(3))
print(mo.square(3))
print(mo.square(4))
print(mo.square(4))
运行结果:
python.exe lru_cache_demo.py
Calculating square of 4
16
16
Calculating square of 5
25
Adding 2 and 3
5
5
Adding 3 and 4
7
Repeating 'hello' 3 times
hellohellohello
hellohellohello
Repeating 'world' 2 times
worldworld
Calculating square of 3
9
9
Calculating square of 4
16
16
注意事项:
1、合理设置缓存大小:lru_cache 的 maxsize 参数控制缓存的大小。如果设为 None,缓存大小将无限制。请根据实际需求设置合适的缓存大小,以避免内存占用过高。
2、注意线程安全:lru_cache 在多线程环境下是线程安全的,但需要确保被缓存的函数本身是线程安全的。
3、传入不可变对象:lru_cache 只能缓存可哈希的对象(如整数、字符串、元组)。传入不可哈希的对象(如列表、字典)将会导致错误。
4、必要时手动进行缓存无效化:缓存条目不会自动失效。如果函数的行为取决于外部状态或依赖的输入数据变化,可能需要手动管理缓存失效或使用其他缓存策略。