在 python/numpy 中,我有一个名为 random_matrix 的 10,000x10,000 数组。我使用 md5 计算 str(random_matrix) 和 random_matrix 本身的散列。字符串版本需要 0.00754404067993 秒,numpy 数组版本需要 1.6968960762 秒。当我把它变成一个 20,000x20,000 数组时,字符串版本需要 0.0778470039368,numpy 数组版本需要 60.641119957 秒。为什么是这样? numpy 数组是否比字符串占用更多内存?另外,如果我想让这些矩阵识别文件名,在计算哈希之前转换为字符串是个好主意,还是有一些缺点?
请您参考如下方法:
str(random_matrix) 不会包含所有矩阵,因为 numpy 用“...”省略了一些东西:
>>> x = np.ones((1000, 1000))
>>> print str(x)
[[ 1. 1. 1. ..., 1. 1. 1.]
[ 1. 1. 1. ..., 1. 1. 1.]
[ 1. 1. 1. ..., 1. 1. 1.]
...,
[ 1. 1. 1. ..., 1. 1. 1.]
[ 1. 1. 1. ..., 1. 1. 1.]
[ 1. 1. 1. ..., 1. 1. 1.]]
因此,当您对 str(random_matrix) 进行哈希处理时,您并没有真正对所有数据进行哈希处理。
参见 this previous question和 this one关于如何散列 numpy 数组。
