当前位置:   article > 正文

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

python使用memory profiler

memory_profile

memory_profiler源码仓库

安装

pip install memory_profiler

使用

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

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

目录结构

  1. |--my.py
  2. |--tests
  3. | |-- test_my_func.py

相关代码

my.py

  1. def func(x: int, y: int):
  2. a = [1] * (10**x)
  3. b = [2] * (2 * 10**y)
  4. del b
  5. return a
'
运行

test_my_func.py

  1. from memory_profiler import LineProfiler, show_results
  2. from my import func
  3. def test_my_func():
  4. lp = LineProfiler()
  5. lp_wrapper = lp(func)
  6. lp_wrapper(6, **{"y": 7})
  7. show_results(lp)

执行结果

pytest ./tests/test_my_func.py -s

好处

  • 以上操作不需要针方法增加装饰器,代码不必反复修改
  • 可以结合单元测试,单独运行测试脚本
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/代码探险家/article/detail/940446
推荐阅读
相关标签
  

闽ICP备14008679号