python - 存储函数过去的结果

标签 python ironpython

我有一个函数,它接受两个数组,进行一些计算,然后返回一个新数组。该函数可能被调用 60,000 次(或 500k,具体取决于),其中多达 25% 的调用次数是在重做之前的计算。

prev_calc = {}
def arrayMagic(ar1,ar2):
    ar1_t = tuple(ar1)
    ar2_t = tuple(ar2)

    if (ar1_t,ar2_t) in prev_calc: 
        return prev_calc[(ar1_t,ar2_t)]
    #some somewhat, but not too expensive function
    res = magicCalc(ar1,ar2)

    prev_calc[(ar1_t,ar2_t)] = res

    return res

ar1 和 ar2 分别是 3 个 float 的数组;例如:[1.1,1.2,2.2] res 也是一个包含 3 个 float 的数组。

问题在于元组转换和字典查找恰好与 magicCalc() 函数所花费的时间非常接近。由于这是我的代码中的主要瓶颈,优化它可以解决很多问题。该函数传递了两个数组,所以我不能将它们作为数组。

有没有一种快速的方法来存储函数过去的结果并返回它们?

最佳答案

这似乎很快......

d = dict()
l1 = [1.1,21.1,31.1,41.1,51.1]
l2 = [12.1,21.1,31.1,41.1,51.1]


def do(a1):
    cacheKey = str(a1) 
    if cacheKey in d:
        print("Read from cache")
        return d[cacheKey]
    else:
        print("calc and cache result")
        d[cacheKey] = sum(a1)
        return d[cacheKey]

print(do(l1))
print(do(l2))
print(do(l1))

关于python - 存储函数过去的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59726341/

相关文章:

当提供 -w 参数时,python 2to3 不会更改 Huey 文件

python - 空列表是否等于 None?

ironpython - spotfire 获取格子面板的名称

ironpython - IronPython 和 IronRuby 的当前标准合规级别

python - 我可以单独获得 Plone 内容的删除权限吗?

python - 仅显示 pandas 中日期范围行的交集

python - 哪些 Python/IronPython Web 开发框架适用于 Microsoft 技术栈?

c#-4.0 - 如何获取静态(编译时)类型的 IDynamicMetaObjectProvider?

python - Pandas 中基于规则的列重命名

python - 如何打印所有可能的树python