CKTIS / Python
`cache_info()`: inspect `lru_cache` statistics
Call `cache_info()` on an `lru_cache`-decorated function to read its hit and miss counts, entry limit, and current number of cached entries.
Version: Python 3.12
Syntax
f.cache_info()If f is decorated with functools.lru_cache, call f.cache_info() with no arguments. The method belongs to the wrapper, not to the functools module. It returns a named tuple that captures the statistics at the time of the read. Reading it neither runs the original function nor changes the cache contents or counters.
hits counts calls served from a cached result; misses counts lookups for which no result was found. maxsize is the entry limit (None means there is no limit), while currsize is the number of entries currently stored, not memory usage in bytes. When a bounded cache is full, adding an entry evicts the least recently used entry; misses are not an eviction count.
Read the statistics after a representative set of calls to see how often results are reused and decide whether to adjust maxsize. These figures do not measure execution time. To clear the cache rather than inspect it, use f.cache_clear().
Examples
from functools import lru_cache
@lru_cache(maxsize=2)
def square(n):
return n * n
for n in (2, 3, 2, 4, 3):
square(n)
info = square.cache_info()
print(f"hits={info.hits}, misses={info.misses}, maxsize={info.maxsize}, currsize={info.currsize}")
Result
hits=1, misses=4, maxsize=2, currsize=2
The second lookup for `2` is the only hit and makes that entry the most recently used. Adding `4` evicts the entry for `3`, so the final call with `3` misses again. There are four misses in total and two entries remain cached.
Related lessons
- Python · Lesson 17 · Intermediate · Version: 3