我比较了将 numpy 数组
写入原始二进制文件的两种简单方法:
# method 1
import numpy
A = numpy.random.randint(1000, size=512*1024*1024) # 2 GB
with open('blah.bin', 'wb') as f:
f.write(A)
和
# method 2
import numpy
A = numpy.random.randint(1000, size=512*1024*1024) # 2 GB
raw_input()
B = A.tostring() # check memory usage of the current process here : 4 GB are used !!
raw_input()
with open('blah.bin', 'wb') as f:
f.write(B)
使用第二种方法,内存使用量加倍(此处为 4 GB)!
为什么.tostring()
经常用于将numpy数组写入文件?
(在 http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.tofile.html 中,解释了 numpy.ndarray.tofile()
可能等同于 file.write(a.tostring())
)
将此类数组写入磁盘时,方法 1 与方法 2 一样正确吗?
最佳答案
文档并没有说 .tofile()
等同于 file.write(a.tostring())
,它只是提到了后者来解释如何如果参数 sep
的值为 ""
,则该参数将起作用。
在第二种方法中,您将创建数组A
的副本,存储在B
中,然后写入文件,而在第一种方法中,这是避免中间复制。
您还应该查看:
np.savetxt()
关于python - 比较将 numpy 数组写入磁盘的两种方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22376218/