Python 函数缓存

  • 作用
    缓存不同参数组合的计算结果,命中缓存可以直接返回结果。
  • 使用示例
    import time
    from functools import lru_cache
    
    
    @lru_cache(maxsize=128)  # 指定128个不同参数组合的调用结果,lru策略,设置为None表示无上限
    def test(step: int, turns: int) -> int:
        total = 0
        for _ in range(turns):
            total += step
        return total
    
    
    # 打印初始的缓存信息
    print(test.cache_info())
    
    
    # 测试缓存创建前函数耗时
    start = time.time()
    test(1, 1000 * 1000 * 30)
    end = time.time()
    print(end - start)
    print(test.cache_info())
    
    # 测试缓存创建后函数耗时
    start = time.time()
    test(1, 1000 * 1000 * 30)
    end = time.time()
    print(end - start)
    print(test.cache_info())
    
    
    # 清理缓存
    test.cache_clear()
    # 测试清理缓存后函数耗时
    start = time.time()
    test(1, 1000 * 1000 * 30)
    end = time.time()
    print(end - start)
  • lru缓存策略补充介绍
    """
    lru策略:
    1.缓存满了怎么办: 当缓存达到 maxsize 限制时,需要为新的缓存项腾出空间
    2.淘汰规则: LRU 会淘汰最长时间没有被访问过的缓存项
    3.访问更新: 每次访问缓存项(无论是读取还是写入),都会将该项标记为"最近使用"
    """
  • 注意事项
    1.参数不能有可变类型,只能是不可变类型。
    2.函数内计算过程不能依赖外部变量,否则可能导致相同参数组合产出不同结果,但是函数给出已缓存结果,导致程序出现bug。

     

posted @ 2025-09-18 14:11  CJTARRR  阅读(9)  评论(0)    收藏  举报