問題描述
調(diào)試python程序時(shí),用下面這段代碼,可以獲得進(jìn)程占用系統(tǒng)內(nèi)存值。程序跑一段時(shí)間后,就能畫出進(jìn)程對(duì)內(nèi)存的占用情況。
def memory_usage_psutil(): # return the memory usage in MB import psutil,os process = psutil.Process(os.getpid()) mem = process.memory_info()[0] / float(2 ** 20) return mem
發(fā)現(xiàn)進(jìn)程的內(nèi)存占用一直再上漲,而這從邏輯上來說是不正常的,所以想到程序可能發(fā)生了Memory Leak。
python程序的Mem Leak
python程序不可能像C/C++一樣出現(xiàn)malloc了的內(nèi)存沒有free這樣的Memory Leak。但也會(huì)遇到“邏輯上沒free”的情況,如下代碼所示。
def foo(a=[]): a.append(time.time()) return a
參數(shù)a這樣可迭代的對(duì)象,稍不注意,它就能增長(zhǎng)的很快。說白了,python的Memory Leak,就是“進(jìn)程占用的內(nèi)存莫名其妙一直再升高”。進(jìn)程占用內(nèi)存一直升高,與邏輯預(yù)期不一致,就可能發(fā)生了Memory Leak。
以下面程序?yàn)槔f明Memory Leak調(diào)試的過程:
def memory_usage_psutil(): # return the memory usage in MB import psutil,os process = psutil.Process(os.getpid()) mem = process.memory_info()[0] / float(2 ** 20) return memdef get_current_obj(a=[]): a.append([0]*1000) return adef main(): obj = [] for i in range(10000): obj = get_current_obj(obj) if(i%100==0): print(memory_usage_psutil())if __name__=='__main__': main()
調(diào)試過程
用pmap -x [pid]查看進(jìn)程占用的堆內(nèi)存大小
首先想到,會(huì)不會(huì)是上面用的memory_usage_psutil函數(shù)統(tǒng)計(jì)錯(cuò)誤呢。
先運(yùn)行程序,再用pmap查看,發(fā)現(xiàn)進(jìn)程內(nèi)存占用確實(shí)很高。多次執(zhí)行該命令,也可以發(fā)現(xiàn)內(nèi)存一直升高。
強(qiáng)制執(zhí)行GC(gc.collect())
在需要執(zhí)行GC的地方加上gc.collect()
def main(): obj = [] for i in range(10000): obj = get_current_obj(obj) import gc;gc.collect() if(i%100==0): print(memory_usage_psutil())
可以看到,強(qiáng)制GC后,程序執(zhí)行變慢,但內(nèi)存依然不斷升高。
使用memory_profiler查看
安裝memory_profiler
pip install -U memory_profiler
用@profile修飾需要查看內(nèi)存的函數(shù)
@profiledef main(): obj = [] for i in range(10000): obj = get_current_obj(obj) if(i%100==0): print(memory_usage_psutil())
用如下命令運(yùn)行程序
python -m memory_profiler main.py
可以看到程序執(zhí)行完成后,輸出結(jié)果如下
Line # Mem usage Increment Line Contents================================================ 12 28.570 MiB 0.000 MiB @profile 13 def main(): 14 28.570 MiB 0.000 MiB obj = [] 15 106.203 MiB 77.633 MiB for i in range(10000): 16 106.203 MiB 0.000 MiB obj = get_current_obj(obj) 17 106.203 MiB 0.000 MiB if(i%100==0): 18 105.445 MiB -0.758 MiB print(memory_usage_psutil())
新聞熱點(diǎn)
疑難解答
圖片精選