python - 占用太多内存-python

标签 python memory numpy yield

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

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/

相关文章:

python - 我可以将参数传递给 SageMaker 估算器的入口点吗?

python - 了解汉诺塔的 Python

python - 从不均匀间隔的文本文件中提取表数据

c - 二维/多维数组的内存映射

python - 图例未出现在 Matplotlib 堆积面积图中

python - 如何从Word2Vec模型中获取词频

gcc - 使用 GCC 4.8.2 的 Asan 时堆栈跟踪中未解析的符号

无法在 ANSI C 中声明具有大行/列 (1446) 的方阵

python - 为什么 scipy.sparse.linalg.eigsh 给出错误的答案?

python - 查看 Python Pandas 相关矩阵条目的常见观察计数的快速方法