前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >memory_profiler的使用

memory_profiler的使用

作者头像
用户1558882
发布2018-04-03 16:11:26
2.6K0
发布2018-04-03 16:11:26
举报
文章被收录于专栏:RgcRgcRgc

作用: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文件

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018-03-05 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档