zoukankan      html  css  js  c++  java
  • Python函数缓存

    函数缓存 (Function caching)

    函数缓存允许我们将一个函数对于给定参数的返回值缓存起来。
    当一个I/O密集的函数被频繁使用相同的参数调用的时候,函数缓存可以节约时间。
    在Python 3.2版本以前我们只有写一个自定义的实现。在Python 3.2以后版本,有个lru_cache的装饰器,允许我们将一个函数的返回值快速地缓存或取消缓存。

    我们来看看,Python 3.2前后的版本分别如何使用它。

    Python 3.2及以后版本

    我们来实现一个斐波那契计算器,并使用lru_cache

    from functools import lru_cache
    
    @lru_cache(maxsize=32)
    def fib(n):
        if n < 2:
            return n
        return fib(n-1) + fib(n-2)
    
    >>> print([fib(n) for n in range(10)])
    # Output: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
    

    那个maxsize参数是告诉lru_cache,最多缓存最近多少个返回值。

    我们也可以轻松地对返回值清空缓存,通过这样:

    fib.cache_clear()
    
  • 相关阅读:
    Core Java Interview Question Answer
    Anagrams
    Permutations II
    Minimum Window Substring
    工厂模式
    How do you design object oriented projects?
    What is Object Oriented Design? (OOD)
    Amazon Interview Question: Design an OO parking lot
    讨论一道求质数的面试题
    Substring with Concatenation of All Words
  • 原文地址:https://www.cnblogs.com/xiao-xue-di/p/10116643.html
Copyright © 2011-2022 走看看