python的memory_profiler模块使用

本文主要介绍了python内存分析工具: memory_profiler,可以展示每一行代码执行所增加的内存,方便做内存调优和排除bug

memory_profiler是第三方模块,需要安装才能使用

pip3.6.exe install memory-profiler

1、直接打印结果到终端上

#coding:utf8
from memory_profiler import profile

@profile
def test1():
    c=list()
    for item in range(10000):
        c.append(item)


if __name__=='__main__':
    test1()

结果如下

Filename: D:/python/test_sip/test_check_es.py

Line #    Mem usage    Increment   Line Contents
================================================
   474     16.6 MiB     16.6 MiB   @profile
   475                             def test1():
   476     16.6 MiB      0.0 MiB       c=list()
   477     17.0 MiB      0.0 MiB       for item in range(10000):
   478     17.0 MiB      0.1 MiB           c.append(item)

Mem usage  执行语句前内存占用

Increment     执行语句后增加的内存

2、定义输出到文件,定义结果保留的小数位

#coding:utf8
from memory_profiler import profile

@profile(precision=4,stream=open('memory_profiler.log','w+'))
def test1():
    c=list()
    for item in range(10000):
        c.append(item)


if __name__=='__main__':
    test1()

结果如下

Filename: D:/python/test_sip/test_check_es.py

Line #    Mem usage    Increment   Line Contents
================================================
   474  16.5391 MiB  16.5391 MiB   @profile(precision=4,stream=open('memory_profiler.log','w+'))
   475                             def test1():
   476  16.5430 MiB   0.0039 MiB       c=list()
   477  16.8906 MiB   0.0039 MiB       for item in range(10000):
   478  16.8906 MiB   0.0391 MiB           c.append(item)

猜你喜欢

转载自www.cnblogs.com/bainianminguo/p/12031200.html