gpt4 book ai didi

python - 散列 Numpy 对象以进行缓存的快速方法

转载 作者:IT老高 更新时间:2023-10-28 20:53:14 26 4
gpt4 key购买 nike

实现一个系统,当涉及到繁重的数学工作时,我希望尽可能少做。

我知道 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com