python 程序内存监控

  • 安装memory_profiler

1

pip install -U memory_profiler

  • 用@profile修饰需要查看内存的函数

1

2

3

4

5

6

7

@profile

def main():   

    obj = []

    for in range(10000):

        obj = get_current_obj(obj)

        if(i%100==0):

            print(memory_usage_psutil())

  • 用如下命令运行程序

1

python -m memory_profiler main.py

可以看到程序执行完成后,输出结果如下

1

2

3

4

5

6

7

8

9

Line #    Mem usage    Increment   Line Contents

================================================

    12   28.570 MiB    0.000 MiB   @profile

    13                             def main():

    14   28.570 MiB    0.000 MiB       obj = []

    15  106.203 MiB   77.633 MiB       for in range(10000):

    16  106.203 MiB    0.000 MiB           obj = get_current_obj(obj)

    17  106.203 MiB    0.000 MiB           if(i%100==0):

    18  105.445 MiB   -0.758 MiB               print(memory_usage_psutil())

这样就能看到导致内存上涨最快的那几行代码。

 

用guppy查看python对象占用的堆内存大小

  • 安装guppy(Python2)

1

pip install guppy

将main修改如下,即可查看python对堆内存的占用量。

1

2

3

4

5

6

7

8

def main():   

    obj = []

    for in range(10000):

        obj = get_current_obj(obj)

        if(i%100==0):

            print(memory_usage_psutil())

            from guppy import hpy;hxx = hpy();heap = hxx.heap()

            print(heap)

下面就是输出结果,python程序中各个对象对内存的占用从大到小排列。

1

2

3

4

5

6

7

8

9

10

11

Index  Count   %     Size   % Cumulative  % Kind (class / dict of class)

    0  10124  22 81944416  95  81944416  95 list

    1  16056  34  1325464   2  83269880  96 str

    2   9147  20   745616   1  84015496  97 tuple

    3    102   0   366480   0  84381976  98 dict of module

    4    287   1   313448   0  84695424  98 dict of type

    5   2426   5   310528   0  85005952  98 types.CodeType

    6   2364   5   283680   0  85289632  99 function

    7    287   1   256960   0  85546592  99 type

    8    169   0   192088   0  85738680  99 dict (no owner)

    9    123   0   142728   0  85881408  99 dict of class

可以从结果中看到,95%的进程内存,都被一个list占用。

还可以通过下面这种方式,查看这个占内存最大的list中的数据类型。

1

from guppy import hpy;hxx = hpy();byrcs = hxx.heap().byrcs; byrcs[0].byid

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值