我正在快取計算緩慢但通常需要多次的值。我有一本看起來像這樣的字典:
stored_values = {
hash1: slow_to_calc_value1
hash2: slow_to_calc_value2
# And so on x5000
}
我正在這樣使用它,如果之前已經計算過,可以快速獲取該值。
def calculate_value_for_item(item):
item_hash = hash_item(item) # Hash the item, used as the dictionary key
stored_value = stored_values.get(item_hash, None)
if stored_value is not None:
return stored_value
calculated_value = do_heavy_math(item) # This is slow and I want to avoid
# Storing the reult for re-use makes me run out of memory at some point
stored_values[item_hash] = calculated_value
return calculated_value
但是,如果我嘗試存盤在整個程式中計算的所有值,我的記憶體就會用完。
如何有效地管理查找字典的大小?這是一個合理的假設,即最近需要的值將來也最有可能需要。
注意事項
- 我已經簡化了很多場景。
- 存盤的值實際上使用了大量記憶體。字典本身并沒有太多的條目,只有幾千個。如果需要,我絕對可以負擔得起一些并行的簿記資料結構。
- 一個理想的解決方案是讓我存盤
n最后需要的值,同時洗掉其余的值。但是任何足夠接近的啟發式方法都足夠好。
uj5u.com熱心網友回復:
你試過使用@lru_cache裝飾器嗎?它似乎完全符合您的要求。
from functools import lru_cache
store_this_many_values = 5
@lru_cache(maxsize=store_this_many_values)
def calculate_value_for_item(item):
calculated_value = do_heavy_math(item)
return calculated_value
@lru_cache 還添加了新功能,這可能會幫助您優化記憶體和/或性能,例如 cache_info
for i in [1,1,1,2]:
calculate_value_for_item(i)
print(calculate_value_for_item.cache_info())
>>> CacheInfo(hits=2, misses=2, maxsize=5, currsize=2)
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/420162.html
標籤:
