实现一个系统,当涉及到繁重的数学工作时,我希望尽可能少做。
我知道 numpy 对象的内存存在问题,因此实现了惰性键缓存以避免整个“过早优化”参数。
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
人们认为什么是“更好的方法”?
最佳答案
借自 this answer ...所以我真的猜这是重复的:
>>> 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
关于python - 散列 Numpy 对象以进行缓存的快速方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5386694/