我编写了一个递归函数,用于穷举生成具有特定特征的矩阵。 该函数如下:
def heavies(rowSums,colSums,colIndex,matH):
if colIndex == len(colSums) - 1:
for stuff in heavy_col_permutations(rowSums,colSums,colIndex):
matH[:,colIndex] = stuff[0]
yield matH.copy()
return
for stuff in heavy_col_permutations(rowSums,colSums,colIndex):
matH[:,colIndex] = stuff[0]
rowSums = stuff[1]
for matrix in heavies(rowSums,colSums,colIndex+1,matH):
yield matrix
heavy_col_permutations是一个函数,它返回一个矩阵的一列,其特征符合我的要求。
问题是heavies会产生很多矩阵,它占用了太多内存。我最终是逐个调用这个函数的,最终占用了太多RAM,并且我的进程被杀死(我在具有内存容量限制的服务器上运行此操作)。如何编写代码以减少内存使用?
程序大致如下:
r = int(argv[1])
n = int(argv[2])
m = numpy.zeros((r,r),numpy.dtype=int32)
for row,col in heavy_listing(r,n):
for matrix in heavies(row,col,0,m):
# do more stuff with matrix
我知道函数heavies是消耗大量内存的地方,我需要减少它。