memory_profiler模块

memory_profiler是用于监视python程序内存使用情况的模块。

官网:https://pypi.org/project/memory-profiler/#description

安装:pip install -U memory_profiler

 

使用方法一:

 

   1.在函数前添加 @profile

 

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

 

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

 

from memory_profiler import profile
import time
@profile
def my_func():
    a = [1] * (10 ** 6)
    b = [2] * (2 * 10 ** 7)
    time.sleep(1)
    del b
    del a
    print("+++++++++")

if __name__ == '__main__':
    my_func()

使用方法二:

  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 

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

from memory_profiler import profile
import time
@profile(precision=4,stream=open('memory_profiler.log','w+'))
def my_func():
    a = [1] * (10 ** 6)
    b = [2] * (2 * 10 ** 7)
    time.sleep(1)
    del b
    del a
    print("+++++++++")

if __name__ == '__main__':
    my_func()

使用方法三:

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

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

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

       mprof clean                                           : 清空所有 .dat文件

 

 

参考链接:https://www.cnblogs.com/kaituorensheng/p/5669861.html

 

posted @ 2019-06-12 19:08  码迷-wjz  阅读(846)  评论(0)    收藏  举报