【问题标题】:Taking up too much memory - python占用太多内存-python
【发布时间】:2013-07-11 05:16:59
【问题描述】:

我编写了一个递归函数,可以详尽地生成具有某些特征的矩阵。 函数是这样的:

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 是一个函数,它只返回具有我需要的特征的矩阵列。

问题在于,由于重量级会产生大量矩阵,因此会占用太多内存。 我最终从另一个函数一个接一个地调用它,最终我占用了太多的 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

而且我知道函数很重是发生大量内存消耗的地方,我只需要减少它。

【问题讨论】:

    标签: python memory numpy yield


    【解决方案1】:

    你可以尝试的事情:

    • 确保heavies() 创建的矩阵副本不在内存中引用。
    • 查看gc 模块,调用collect() 并使用set_threshold()
    • 将函数重写为迭代而不是递归

    【讨论】:

      猜你喜欢
      • 2020-05-18
      • 1970-01-01
      • 1970-01-01
      • 2017-04-14
      • 2015-10-14
      • 2013-07-18
      • 1970-01-01
      • 1970-01-01
      • 2013-08-26
      相关资源
      最近更新 更多