您的位置:首页 > 其它

memory_profiler的使用

2018-03-05 21:54 537 查看

作用:memory_profiler是用来分析每行代码的内存使用情况

使用方法一:

   1.在函数前添加 @profile

        2.运行方式: python -m memory_profiler memory_profiler_test.py     

  此方法缺点:在调试 和 实际项目运行时 要 增删 @profile 此装饰器

代码如下:

1 #coding:utf8
2
3 @profile
4 def test1():
5     c=0
6     for item in xrange(100000):
7         c+=1
8     print c
9
10 if __name__=='__main__':
11     test1()

输出结果:

rgc@rgc:~/baidu_eye/carrier/test$ python -m memory_profiler memory_profiler_test.py
100000
Filename: memory_profiler_test.py

Line #    Mem usage    Increment   Line Contents
================================================
5   21.492 MiB   21.492 MiB   @profile
6                             def test1():
7   21.492 MiB    0.000 MiB       c=0
8   21.492 MiB    0.000 MiB       for item in xrange(100000):
9   21.492 MiB    0.000 MiB           c+=1
10   21.492 MiB    0.000 MiB       print c

名词含义为

  Mem usage: 内存占用情况

  Increment: 执行该行代码后新增的内存

 

使用方法二:

  1.先导入:    from memory_profiler import profile

       2.函数前加装饰器:   @profile(precision=4,stream=open('memory_profiler.log','w+'))            

            参数含义:precision:精确到小数点后几位 

                 stream:此模块分析结果保存到 'memory_profiler.log' 日志文件。如果没有此参数,分析结果会在控制台输出

  运行方式:直接跑此脚本  python memory_profiler_test.py

  此方法优点:解决第一种方法的缺点,在 不需要 分析时,直接注释掉此行

1 #coding:utf8
2 from memory_profiler import profile
3
4 @profile(precision=4,stream=open('memory_profiler.log','w+'))
5 # @profile
6 def test1():
7     c=0
8     for item in xrange(100000):
9         c+=1
10     print c
11
12 if __name__=='__main__':
13     test1()

 

使用方法三:

  脚本代码和方法二一样,但是 运行方式不同

  mprof run memory_profiler_test.py       : 分析结果会保存到一个 .dat格式文件中

  mprof plot                                              : 把结果以图片到方式显示出来(直接在本目录下运行此命令即可,程序会自动找出.dat文件) (要安装 

pip install matplotlib

       mprof clean                                           : 清空所有 .dat文件

 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: