如何使用大型numpy数组优化Python中的内存分配?

时间:2019-02-09 15:17:03

标签: python python-3.x numpy h5py

我通过以下方式使用numpy(1.15.4)和h5py(2.9.0):

import numpy as np
import h5py
import sys

Ns, N, L, Nz = (40, 80, 3240, 160)
largeArray = np.zeros((Ns,N, L, Nz), dtype=complex)

for ids in range(Ns):
    for n in range(N):
        for l in range(L):
            #calling a bunch of numerical operations with pybind11 
            #and storing the results into a largeArray
            largeArray[ids, n, l]=ids+n+l*1j

f = h5py.File('myFile.hdf5', 'w')
f.create_dataset('largeArray', data=largeArray)
print('content:', largeArray.nbytes)
print('size:', sys.getsizeof(largeArray))

必须分配大量数据26.5GB,并且系统报告148 GB的内存使用情况。我假设内存管理器正在与硬盘交换内存中的数据,对吗?我使用pybind11来包装数字运算,然后开始将数据分解为最外层循环(ids)中的块,以使用mpih5py存储数据在parallel中,但有时存储空间不足。知道什么会耗尽所有内存吗?

0 个答案:

没有答案