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

标签 python performance numpy

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

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

相关文章:

使用 asyncio 的 Python 简单套接字客户端/服务器

performance - Azure Web 和辅助角色 - 2 个小型实例还是 1 个中型实例?

python - 在 Pandas 数据框和平均数组中按列分组

python - Numpy View Reshape Without Copy(二维移动/滑动窗口、步幅、屏蔽内存结构)

python - 使用 numpy 操作一个数组中的数据以影响另一个数组

python - 为什么你要 'import' Python 标准库函数?

python - 将字节数组转换为字符串并返回

python - 发送低级原始 tcp 数据包 python

java - 优化文件下载

Java JVM 或 Eclipse 启动开销