Python利用memory_profiler查看內(nèi)存占用情況
簡介
memory_profiler是第三方模塊,用于監(jiān)視進(jìn)程的內(nèi)存消耗以及python程序內(nèi)存消耗的逐行分析。它是一個(gè)純python模塊,依賴于psutil模塊。
安裝
pip install memory_profiler
使用方法
1、通過裝飾器運(yùn)行
@profile def func1():
2、通過命令行運(yùn)行
python -m memory_profiler test_code.py
案例源碼:
# -*- coding: utf-8 -*-
# time: 2022/6/11 21:17
# file: test_code.py
# 公眾號: 玩轉(zhuǎn)測試開發(fā)
from memory_profiler import profile
loop = 50000
@profile
def func1():
s1 = [i for i in range(loop)]
s2 = []
for i in range(loop):
if i & 1 == 1:
s2.append(i)
result = sum(s1) + sum(s2)
del s1
del s2
return result
if __name__ == '__main__':
result = func1()
print(result)
方法1運(yùn)行結(jié)果:

方法2運(yùn)行結(jié)果:

補(bǔ)充
下面小編為大家整理了一下memory_profiler的一些使用
1、直接打印結(jié)果到終端上
#coding:utf8
from memory_profiler import profile
@profile
def test1():
c=list()
for item in range(10000):
c.append(item)
if __name__=='__main__':
test1()
結(jié)果如下
Filename: D:/python/test_sip/test_check_es.py
Line # Mem usage Increment Line Contents
================================================
474 16.6 MiB 16.6 MiB @profile
475 def test1():
476 16.6 MiB 0.0 MiB c=list()
477 17.0 MiB 0.0 MiB for item in range(10000):
478 17.0 MiB 0.1 MiB c.append(item)
2、定義輸出到文件,定義結(jié)果保留的小數(shù)位
#coding:utf8
from memory_profiler import profile
@profile(precision=4,stream=open('memory_profiler.log','w+'))
def test1():
c=list()
for item in range(10000):
c.append(item)
if __name__=='__main__':
test1()
結(jié)果如下
Filename: D:/python/test_sip/test_check_es.py
Line # Mem usage Increment Line Contents
================================================
474 16.5391 MiB 16.5391 MiB @profile(precision=4,stream=open('memory_profiler.log','w+'))
475 def test1():
476 16.5430 MiB 0.0039 MiB c=list()
477 16.8906 MiB 0.0039 MiB for item in range(10000):
478 16.8906 MiB 0.0391 MiB c.append(item)
到此這篇關(guān)于Python利用memory_profiler查看內(nèi)存占用情況的文章就介紹到這了,更多相關(guān)Python memory_profiler查看內(nèi)存占用內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python?PyQt拖動(dòng)控件對齊到網(wǎng)格的方法步驟
pyqt是一個(gè)用于創(chuàng)建GUI應(yīng)用程序的跨平臺(tái)工具包,它將python與qt庫融為一體,下面這篇文章主要給大家介紹了關(guān)于Python?PyQt拖動(dòng)控件對齊到網(wǎng)格的方法步驟,需要的朋友可以參考下2022-12-12
使用tensorboard可視化loss和acc的實(shí)例
今天小編就為大家分享一篇使用tensorboard可視化loss和acc的實(shí)例,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-01-01
Python進(jìn)程崩潰AttributeError異常問題解決
這篇文章主要介紹了Python進(jìn)程崩潰(AttributeError異常)問題解決,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下方法2023-06-06
使用opencv識別圖像紅色區(qū)域,并輸出紅色區(qū)域中心點(diǎn)坐標(biāo)
這篇文章主要介紹了使用opencv識別圖像紅色區(qū)域,并輸出紅色區(qū)域中心點(diǎn)坐標(biāo),具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-06-06

