只介紹簡單的使用, 更多使用方法請查看官方文檔
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: str, cumulative: bool=False)
將統計信息作為 Statistic
實例分組依據 key_type :
key_type |
描述 |
---|---|
|
文件名 |
|
文件名和行號 |
|
追溯 |
如果 累積的 是 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)
歡迎補充
目前使用過的, 還比較好使的是這些