快速哈希Numpy对象以便缓存

26 投票
3 回答
15672 浏览
提问于 2025-04-16 14:10

我想建立一个系统,尽量减少自己在复杂数学计算上的工作量。

我知道在使用numpy对象时,缓存(memoisation)会有一些问题,因此我实现了一个懒惰键缓存,以避免“过早优化”的争论。

def magic(numpyarg,intarg):
    key = str(numpyarg)+str(intarg)

    try:
        ret = self._cache[key]
        return ret
    except:
        pass

    ... here be dragons ...
    self._cache[key]=value
    return value

不过,由于字符串转换需要花费不少时间……

t=timeit.Timer("str(a)","import numpy;a=numpy.random.rand(10,10)")
t.timeit(number=100000)/100000 = 0.00132s/call

大家有什么建议,认为哪种方法更好呢?

3 个回答

2

对于小的numpy数组,这种方法也可能适用:

tuple(map(float, a))

这里的a指的是那个numpy数组。

7

有一个叫做 joblib 的工具包可以用来做这个。这个信息是从 这个 问题中找到的。

from joblib import Memory
location = './cachedir'
memory = Memory(location)

# Create caching version of magic
magic_cached = memory.cache(magic)
result = magic_cached(...)

# Or (for one-time use)
result = memory.eval(magic, ...)
30

这段内容是引用自这个回答... 所以我想这其实是个重复的问题:

>>> import hashlib
>>> import numpy
>>> a = numpy.random.rand(10, 100)
>>> b = a.view(numpy.uint8)
>>> hashlib.sha1(b).hexdigest()
'15c61fba5c969e5ed12cee619551881be908f11b'
>>> t=timeit.Timer("hashlib.sha1(a.view(numpy.uint8)).hexdigest()", 
                   "import hashlib;import numpy;a=numpy.random.rand(10,10)") 
>>> t.timeit(number=10000)/10000
2.5790500640869139e-05

撰写回答