How can you see whether repeated feature conversions hit a cache?

lru_cache memoizes results by hashable call arguments. cache_info reports hits, misses and current occupancy.

Python example and interpretation

Squaring the same integer twice computes it once. Include every result-changing setting in the key to avoid reusing a stale feature version.

from functools import lru_cache
square=lru_cache(maxsize=2)(lambda x:x*x)
square(4)
square(4)
square.cache_info()._asdict()

Result {'hits': 1, 'misses': 1, 'maxsize': 2, 'currsize': 1}

中文

如何判断重复的特征转换是否命中了缓存?

lru_cache 按可哈希的调用参数保存返回值,cache_info 提供命中、未命中和占用情况。

Python 算例与适用条件

对同一整数调用两次平方函数只计算一次。缓存键应覆盖所有影响结果的配置,否则可能读到旧版本特征。

from functools import lru_cache
square=lru_cache(maxsize=2)(lambda x:x*x)
square(4)
square(4)
square.cache_info()._asdict()

结果 {'hits': 1, 'misses': 1, 'maxsize': 2, 'currsize': 1}

References / 参考来源

Keep reading / 继续阅读