我正在用 Python 开发一个光线追踪项目,我希望实现一个基本的缓存机制来提高性能。我想避免使用 functools 和类。
custom_cache = {}
def ray_trace(x, y, z):
key = (x, y, z)
if key in custom_cache:
return custom_cache[key]
computed_result = ...
custom_cache[key] = computed_result
return computed_result
如何改进或优化这个缓存机制?我应该牢记哪些最佳实践或注意事项?我对使用类和 functools 的替代方案特别感兴趣。预先感谢您的帮助!
您可以限制缓存的大小以防止其无限增长。当缓存达到其限制时,您可以删除最近使用的项目。您可以这样修改您的代码:
from collections import OrderedDict
custom_cache = OrderedDict()
CACHE_SIZE_LIMIT = 1000
def ray_trace(x, y, z):
key = (x, y, z)
if key in custom_cache:
# Move the key to the end to mark it as most recently used
custom_cache.move_to_end(key)
return custom_cache[key]
computed_result = ...
custom_cache[key] = computed_result
if len(custom_cache) > CACHE_SIZE_LIMIT:
custom_cache.popitem(last=False)
return computed_result