Sub topic 10
Measuring and clearing a cache
This chapter assumes you can apply functools.cache or functools.lru_cache to a function, as covered in the previous two chapters. It shows how to check whether a cache is working and how to empty it.
Why measure a cache
A cache saves time only if calls repeat. If every call uses new arguments, the cache stores results nobody asks for again. It then costs memory and gives nothing back. Every function wrapped by cache or lru_cache has two methods that answer this question: cache_info() and cache_clear().
Reading cache_info
cache_info() returns a named tuple with four fields:
| Field | Meaning |
|---|---|
| `hits` | Calls answered from the cache |
| `misses` | Calls that ran the function |
| `maxsize` | The size limit, or `None` for an unbounded cache |
| `currsize` | The number of entries stored now |
from functools import lru_cache
@lru_cache(maxsize=128)
def slow_square(n):
return n * n
for n in [1, 2, 3, 1, 2, 3, 1]:
slow_square(n)
info = slow_square.cache_info()
print(info) # CacheInfo(hits=4, misses=3, maxsize=128, currsize=3)
total = info.hits + info.misses
print(f"hit rate: {info.hits / total:.0%}") # hit rate: 57%The first three calls are misses because each argument is new. The last four repeat earlier arguments, so they are hits. Because the result is a named tuple, you can read fields by name, as in info.hits.
The hit rate is hits / (hits + misses). A rate near zero means the arguments rarely repeat, and caching is probably the wrong tool for that function.
Reading currsize and maxsize
currsize shows how much memory pressure the cache creates. With lru_cache(maxsize=2), currsize never goes above 2, because older entries are evicted. With cache, maxsize is None and currsize grows with every new set of arguments. A currsize that keeps rising in a long-running program is a warning sign, and lru_cache with a limit is the usual fix.
Clearing with cache_clear
cache_clear() removes every stored result and resets the counters to zero.
from functools import lru_cache
@lru_cache(maxsize=2)
def square(n):
print(f"computing {n}")
return n * n
square(1)
square(2)
square(1) # cache hit
print(square.cache_info()) # CacheInfo(hits=1, misses=2, maxsize=2, currsize=2)
square.cache_clear()
print(square.cache_info()) # CacheInfo(hits=0, misses=0, maxsize=2, currsize=0)
square(1) # prints "computing 1" againTypical reasons to clear a cache:
- Stale data. The function reads a file or setting that changed, and old results are now wrong.
- Tests. Cached results from one test can leak into the next. Calling
cache_clear()in test setup keeps tests independent. - Memory. You want to release stored results after a large batch job.
cache_clear() empties the whole cache. You cannot remove one entry. If you need that, a plain dictionary you manage yourself is a better fit.
Gotcha: inspecting a decorated cached function
The last chapter's decorator pattern puts a wraps-based decorator on top of a cached function. The outer function is then the plain wrapper, and it has no cache_info method. wraps copies the name, docstring, and __dict__, but it does not add the cache methods. It does set __wrapped__, which points to the cached function underneath.
import functools
from functools import cache
def log_calls(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
print(f"calling {func.__name__}{args}")
return func(*args, **kwargs)
return wrapper
@log_calls
@cache
def double(n):
return n * 2
double(4)
double(4)
print(double.__wrapped__.cache_info())
# CacheInfo(hits=1, misses=1, maxsize=None, currsize=1)Calling double.cache_info() here raises AttributeError. Go through __wrapped__ to reach the cache. If you order the decorators the other way, with @cache on top, cache_info works directly. The logging then runs only on misses, because hits never reach the inner function.
Summary
cache_info()reports hits, misses,maxsize, andcurrsize.- A low hit rate or a steadily growing
currsizemeans the cache needs a rethink. cache_clear()empties the cache and resets the counters. It cannot remove single entries.- Behind a
wraps-based decorator, reach the cache through__wrapped__.
Exercise
A function f is decorated with @lrucache(maxsize=1). You call f(1), f(1), f(2), f(1) in that order. What does f.cacheinfo() report?
Show answer
CacheInfo(hits=1, misses=3, maxsize=1, currsize=1). The first call f(1) is a miss. The second f(1) is a hit. f(2) is a miss and evicts the entry for 1, because only one entry fits. The final f(1) is a miss again, because it was evicted. That gives 1 hit and 3 misses. The cache then holds only the result for 1.