1 | pip install - U memory_profiler |
1 2 3 4 5 6 7 | @profile def main(): obj = [] for i 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 i 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对象占用的堆内存大小
将main修改如下,即可查看python对堆内存的占用量。
1 2 3 4 5 6 7 8 | def main(): obj = [] for i 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 |