【发布时间】:2014-04-18 01:05:20
【问题描述】:
我比较了将numpy array 写入原始二进制文件的两种简单方法:
# 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 一样正确?
【问题讨论】: