占用过多内存 - Python

3

我编写了一个递归函数,用于穷举生成具有特定特征的矩阵。 该函数如下:

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是消耗大量内存的地方,我需要减少它。

1个回答

1

您可以尝试以下方法:

  • 确保由 heavies() 创建的矩阵副本没有在内存中被引用。
  • 查看 gc 模块,调用 collect() 并尝试使用 set_threshold() 进行优化。
  • 将函数改写为迭代方式,而非递归方式。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接