擅长:python、mysql、java
<p>您可以使用<code>lru_cache</code>模块中的<code>functools</code>。<br/>
<a href="https://docs.python.org/3/library/functools.html" rel="nofollow noreferrer">https://docs.python.org/3/library/functools.html</a><br/>
如文件所述</p>
<blockquote>
<p>Decorator to wrap a function with a memoizing callable that saves up to the maxsize most recent calls. It can save time when an expensive or I/O bound function is periodically called with the same arguments</p>
</blockquote>
<p>如果将maxsize设置为<code>None</code>,则缓存将不受限制地增长。你知道吗</p>
<pre><code>from functools import lru_cache
@lru_cache(maxsize = None)
def rec(n):
if n < 1:
return 1
return rec(n // 4) + rec(n // 2)
print(rec(12345678987654321))
</code></pre>
<p>时间度量:</p>
<pre><code>times = timeit.timeit(setup = 'from __main__ import rec',
stmt = 'print(rec(12345678987654321))', number = 1)
</code></pre>
<p>与<code>lru_cache</code></p>
<pre><code>225851433717
0.00023956200311658904
</code></pre>
<p>没有<code>lru_cache</code></p>
<pre><code>More than 2 minutes
</code></pre>