首页 > 编程语言 > 详细

Python 检查代码占用内存 工具和模块

时间:2019-11-28 18:32:46      阅读:86      评论:0      收藏:0      [点我收藏+]

只介绍简单的使用, 更多使用方法请查看官方文档

tracemalloc

官方文档

tracemalloc文档地址 

使用

import tracemalloc

tracemalloc.start()

# 运行程序
main()

snapshot = tracemalloc.take_snapshot()
top_stats = snapshot.statistics(lineno)

# 输出前10条测试结果
print("[ Top 10 ]")
for stat in top_stats[:10]:
    print(stat)

statistics(key_type: strcumulative: bool=False)

将统计信息作为 Statistic 实例分组依据 key_type :

key_type

描述

‘filename‘

文件名

‘lineno‘

文件名和行号

‘traceback‘

追溯

如果 累积的 是 True ,累积跟踪的所有帧的内存块大小和计数,而不仅仅是最新帧。累积模式只能用于 key_type 等于 ‘filename‘ 和 ‘lineno‘ .

结果按以下顺序从大到小排序: Statistic.size , Statistic.count 然后由 Statistic.traceback .

memory_profiler

官方文档

https://pypi.org/project/memory-profiler/

安装

pip install -U memory_profiler

在脚本外使用

@profile
def my_func():
    a = [1] * (10 ** 6)
    b = [2] * (2 * 10 ** 7)
    del b
    return a

if __name__ == __main__:
    my_func()

运行:

python -m memory_profiler example.py

在文件中使用

from memory_profiler import profile

@profile
def my_func():
    a = [1] * (10 ** 6)
    b = [2] * (2 * 10 ** 7)
    del b
    return a

if __name__ == __main__:
    my_func()

运行:

python example.py

Heartrate

项目地址

https://github.com/alexmojaki/heartrate

安装

pip install --user heartrate

使用

# 在需要测试的文件中插入
import heartrate; heartrate.trace(browser=True)

欢迎补充

目前使用过的, 还比较好使的是这些

 

 

Python 检查代码占用内存 工具和模块

原文:https://www.cnblogs.com/mswei/p/11951609.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!