如何剖析Python中的内存使用情况?

发布于 2021-02-02 23:15:52

最近,我对算法产生了兴趣,并通过编写一个简单的实现,然后以各种方式对其进行了优化来开始探索它们。

我已经熟悉了用于分析运行时的标准Python模块(对于大多数事情,我发现IPython中的timeit magic函数就足够了),但是我也对内存使用感兴趣,因此我也可以探索这些折衷方案(例如,缓存先前计算的值与根据需要重新计算它们的表的成本)。是否有一个模块可以为我配置给定功能的内存使用情况?

关注者
0
被浏览
102
1 个回答
  • 面试哥
    面试哥 2021-02-02
    为面试而生,有面试问题,就找面试哥。

    在这里已经回答了这个问题:Python memory profiler

    基本上,你可以执行以下操作(引用自Guppy-PE):

    >>> from guppy import hpy; h=hpy()
    >>> h.heap()
    Partition of a set of 48477 objects. Total size = 3265516 bytes.
     Index  Count   %     Size   % Cumulative  % Kind (class / dict of class)
         0  25773  53  1612820  49   1612820  49 str
         1  11699  24   483960  15   2096780  64 tuple
         2    174   0   241584   7   2338364  72 dict of module
         3   3478   7   222592   7   2560956  78 types.CodeType
         4   3296   7   184576   6   2745532  84 function
         5    401   1   175112   5   2920644  89 dict of class
         6    108   0    81888   3   3002532  92 dict (no owner)
         7    114   0    79632   2   3082164  94 dict of type
         8    117   0    51336   2   3133500  96 type
         9    667   1    24012   1   3157512  97 __builtin__.wrapper_descriptor
    <76 more rows. Type e.g. '_.more' to view.>
    >>> h.iso(1,[],{})
    Partition of a set of 3 objects. Total size = 176 bytes.
     Index  Count   %     Size   % Cumulative  % Kind (class / dict of class)
         0      1  33      136  77       136  77 dict (no owner)
         1      1  33       28  16       164  93 list
         2      1  33       12   7       176 100 int
    >>> x=[]
    >>> h.iso(x).sp
     0: h.Root.i0_modules['__main__'].__dict__['x']
    >>> 
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看