Nim中如何为多参数慢计算函数实现自动结果缓存
Nim 计算函数自动缓存实现需求
当前存在数据加载、计算流程运行速度偏慢的问题,计划通过缓存历史计算结果减少重复计算开销,提升后续运行效率。
功能需求说明
需要实现两类核心计算能力:
- 按指定日期将目标币种换算为等值美元
- 计算指定币种、对应日期的居民消费价格指数(CPI, Consumer Price Index)
预期调用效果如下:
echo to_usd("EUR", (2000, 1, 1), false) # => 0.846 echo to_cpi("USD", (2000, 1, 1)) # => 144.0
期望的缓存封装效果
希望不需要为每个函数手动编写重复的缓存逻辑,直接通过通用封装器对慢计算函数做装饰,自动生成带缓存的可调用版本,目标写法类似:
# 原始慢计算函数 proc to_usd_slow*(currency: string, time: TimeD): float = # 实际的耗时计算逻辑 1.0 # 通过cache封装自动生成带缓存的可调用版本 proc to_usd* = cache(to_usd_slow)
当前手动实现的缓存代码逻辑
目前手动编写缓存的通用流程为:为每个慢函数单独定义缓存key类型、实现对应的哈希规则、初始化独立的缓存表实例、在函数入口增加缓存查询、未命中则执行慢计算并写入缓存的分支判断。
核心可运行代码如下:
import hashes, tables # 为元组/自定义类型生成通用哈希值 proc autohash*[T: tuple|object](o: T): Hash = for f in o.fields: result = result !& f.hash type TimeD = tuple[year, month, day: int] PointM = tuple[time: TimeD, value: float] # 慢计算逻辑:CPI 居民消费价格指数 proc to_cpi_slow(currency: string, time: TimeD, extrapolate: bool): float = # 实际的耗时计算逻辑 1.0 # 手动实现的CPI函数缓存逻辑 type ToCpiKey = (string, TimeD, bool) proc hash(v: ToCpiKey): Hash = v.autohash var to_cpi_cache = init_table[ToCpiKey, float]() proc to_cpi*(currency: string, time: TimeD, extrapolate: bool): float = let key: ToCpiKey = (currency, time, extrapolate) if key notin to_cpi_cache: to_cpi_cache[key] = to_cpi_slow(currency, time, extrapolate) to_cpi_cache[key] # 慢计算逻辑:币种换算 proc to_usd_slow*(currency: string, time: TimeD): float = # 实际的耗时计算逻辑 1.0 # 手动实现的币种换算函数缓存逻辑 type ToUsdMKey = (string, TimeD) proc hash(v: ToUsdMKey): Hash = v.autohash var to_usd_cache = init_table[ToUsdMKey, float]() proc to_usd*(currency: string, time: TimeD): float = let key: ToUsdMKey = (currency, time) if not(key in to_usd_cache): to_usd_cache[key] = to_usd_slow(currency, time) to_usd_cache[key] # 最终调用示例 echo to_cpi("USD", (2000, 1, 1), false) echo to_usd("EUR", (2000, 1, 1))
内容的提问来源于stack exchange,提问作者Alex Craft
相关产品推荐
相关产品推荐

