我编写了一个递归函数,它可以详尽地生成具有某些特征的矩阵。 函数是这样的:
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 是一个函数,它只返回具有我需要的特征的矩阵的一列。
问题在于,由于权重会产生大量矩阵,因此会占用太多内存。 我最终从另一个函数一个一个地调用它,最终我占用了太多的内存并且我的进程被杀死了(我在有内存上限的服务器上运行它)。我该如何编写它以使其使用更少的内存?
程序看起来像这样:
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 是发生大量内存消耗的地方,我只需要减少它。
最佳答案
你可以尝试的事情:
- 确保
heavies()
创建的矩阵副本不会在内存中保持引用。 - 查看
gc
模块,调用collect()
并使用set_threshold()
- 将函数重写为迭代而不是递归
关于python - 占用太多内存-python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17618708/