python使用memory_profiler分析代码运行内存占用

memory_profile

memory_profiler源码仓库

安装

pip install memory_profiler

使用

请参考以下文章,写的很详细 【精选】Python代码优化工具——memory_profiler_被Python玩的Kenny的博客-CSDN博客

本文要增加介绍的是API使用

目录结构

|--my.py
|--tests
|  |-- test_my_func.py

相关代码

my.py

def func(x: int, y: int):
    a = [1] * (10**x)
    b = [2] * (2 * 10**y)
    del b
    return a

test_my_func.py

from memory_profiler import LineProfiler, show_results

from my import func

def test_my_func():
    lp = LineProfiler()
    lp_wrapper = lp(func)
    lp_wrapper(6, **{"y": 7})
    show_results(lp)

执行结果

pytest ./tests/test_my_func.py -s

好处

  • 以上操作不需要针方法增加装饰器,代码不必反复修改
  • 可以结合单元测试,单独运行测试脚本
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值