只介绍简单的使用, 更多使用方法请查看官方文档
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: str, cumulative: bool=False)
将统计信息作为 Statistic
实例分组依据 key_type :
key_type |
描述 |
---|---|
|
文件名 |
|
文件名和行号 |
|
追溯 |
如果 累积的 是 True
,累积跟踪的所有帧的内存块大小和计数,而不仅仅是最新帧。累积模式只能用于 key_type 等于 ‘filename‘
和 ‘lineno‘
.
结果按以下顺序从大到小排序: Statistic.size
, Statistic.count
然后由 Statistic.traceback
.
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
https://github.com/alexmojaki/heartrate
pip install --user heartrate
# 在需要测试的文件中插入 import heartrate; heartrate.trace(browser=True)
目前使用过的, 还比较好使的是这些
原文:https://www.cnblogs.com/mswei/p/11951609.html