Python3:程序占用的内存比预期的多得多

2024-04-25 21:25:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我的python程序占用的内存比内存分析工具预期的或返回的内存要多得多。我需要一个策略来找到内存泄漏并修复它。在

详细的

我正在64位Linux机器上运行python3脚本。几乎所有代码都捆绑在一个对象中:

obj = MyObject(*myArguments)
result = obj.doSomething()
print(result)

obj的创建过程中,程序读取一个大小约为100MB的文本文件。由于我以多种方式保存信息,所以我希望整个对象占用几百MB的内存。在

实际上,使用包pympler中的asizeof.asized(obj)来测量它的大小,返回大约123MB。但是,top告诉我我的程序占用了大约1GB的内存。在

我知道方法中的局部变量将占用更多的RAM。然而,在我的代码中,我发现这些局部变量都没有那么大。我用asizeof.asized再次检查了这个。在

我并不担心脚本需要1GB内存。但是,我并行执行一些方法(分12个过程):

^{pr2}$

这使得总内存使用量变为8GB,即使我将所有大对象都放在共享内存中:

self.myLargeNumPyArray = sharedmem.copy(self.myLargeNumPyArray)

我向测试程序保证内存确实是共享的。在

通过asizeof检查,我在每个子流程中获得

  • asizeof.asized(self)是1MB(也就是说,比“原始”对象小得多——可能是由于共享内存的缘故,共享内存不被双倍计算)
  • asizeof.asized(myOneAndOnlyBigLocalVariable)是230MB。在

总之,我的程序应该占用不超过123MB+12*230MB=2.8GB<;<;8GB。那么,为什么这个程序需要这么多内存?在

一种解释可能是有一些隐藏的部分(垃圾?)在被复制的对象中,当程序并行运行时。在

有人知道找出内存泄漏在哪里的策略吗?我怎么能修好它?

我读过很多关于内存配置的线程,例如Profiling memory in python 3Is there any working memory profiler for Python3Which Python memory profiler is recommended?,或{a5},但是所有推荐的工具都没有解释内存的使用。在


更新

我被要求提供一个最小的代码示例。下面的代码显示了与我的原始代码相同的并行部分内存消耗问题。我已经解决了代码中非并行部分的问题,那就是我有一个数据类型为object的大型numpy数组作为对象变量。由于此数据类型,数组无法放入共享内存,asized只返回浅层大小。感谢@user2357112帮我解决了这个问题!在

因此,我想集中讨论并行部分的问题:在方法singleSourceShortestPaths中插入值(下面用注释标记)将内存消耗从大约1.5GB更改为10GB。有什么办法解释这种行为吗?在

import numpy as np
from heapdict import heapdict
from pympler import asizeof
import sharedmem

class RoadNetwork():

    strType = "|S10"

    def __init__(self):

        vertexNo = 1000000
        self.edges = np.zeros(1500000, dtype = {"names":["ID", "from_to", "from_to_original", "cost", "inspection", "spot"], 
                                                   'formats':[self.strType, '2int', '2'+self.strType, "double", "3bool", "2int", "2int"]})
        self.edges["ID"] = np.arange(self.edges.size)
        self.edges["from_to_original"][:vertexNo, 0] = np.arange(vertexNo)
        self.edges["from_to_original"][vertexNo:, 0] = np.random.randint(0, vertexNo, self.edges.size-vertexNo)
        self.edges["from_to_original"][:,1] = np.random.randint(0, vertexNo, self.edges.size)

        vertexIDs = np.unique(self.edges["from_to_original"])
        self.vertices = np.zeros(vertexIDs.size, {"names":["ID", "type", "lakeID"], 
                                                  'formats':[self.strType, 'int', self.strType]})

    def singleSourceShortestPaths(self, sourceIndex):

        vertexData = np.zeros(self.vertices.size, dtype={"names":["predecessor", "edge", "cost"], 
                                         'formats':['int', "2int", "double"]})

        queue = np.zeros((self.vertices.size, 2), dtype=np.double)

        #Crucual line!! Commetning this decreases memory usage by 7GB in the parallel part
        queue[:,0] = np.arange(self.vertices.size)

        queue = heapdict(queue)

        print("self in singleSourceShortestPaths", asizeof.asized(self))
        print("queue in singleSourceShortestPaths", asizeof.asized(queue))
        print("vertexData in singleSourceShortestPaths", asizeof.asized(vertexData))

        # do stuff (in my real program Dijkstra's algorithm would follow)
        # I inserted this lines as an ugly version for 'wait()' to
        # give me enough time to measure the memory consumption in 'top'
        for i in range(10000000000):
            pass

        return vertexData

    def determineFlowInformation(self):
        print("self in determineFlowInformation", asizeof.asized(self))
        f = lambda i: self.singleSourceShortestPaths(i)
        self.parmap(f, range(30))

    def parmap(self, f, argList):
        """
        Executes f(arg) for arg in argList in parallel
        returns a list of the results in the same order as the 
        arguments, invalid results (None) are ignored
        """
        self.__make_np_arrays_sharable()
        with sharedmem.MapReduce() as pool:
            results, to_do_list = zip(*pool.map(f, argList))
        return results

    def __make_np_arrays_sharable(self):
        """
        Replaces all numpy array object variables, 
        which should have the same  
        behaviour / properties as the numpy array
        """
        varDict = self.__dict__
        for key, var in varDict.items():
            if type(var) is np.ndarray:
                varDict[key] = sharedmem.copy(var)

if __name__ == '__main__':
    network = RoadNetwork()

    print(asizeof.asized(network, detail=1))
    for key, var in network.__dict__.items():
        print(key, asizeof.asized(var))

    network.determineFlowInformation()

Tags: theto内存代码infromself程序