memory_profiler的使用


作用:memory_profiler是用來分析每行代碼的內存使用情況

使用方法一:

   1.在函數前添加 @profile

        2.運行方式: python -m memory_profiler memory_profiler_test.py     

  此方法缺點:在調試 和 實際項目運行時 要 增刪 @profile 此裝飾器

代碼如下:

 1 #coding:utf8
 2 
 3 @profile
 4 def test1():
 5     c=0
 6     for item in xrange(100000):
 7         c+=1
 8     print c
 9 
10 if __name__=='__main__':
11     test1()

輸出結果:

rgc@rgc:~/baidu_eye/carrier/test$ python -m memory_profiler memory_profiler_test.py 
100000
Filename: memory_profiler_test.py

Line #    Mem usage    Increment   Line Contents
================================================
     5   21.492 MiB   21.492 MiB   @profile
     6                             def test1():
     7   21.492 MiB    0.000 MiB       c=0
     8   21.492 MiB    0.000 MiB       for item in xrange(100000):
     9   21.492 MiB    0.000 MiB           c+=1
    10   21.492 MiB    0.000 MiB       print c

名詞含義為

  Mem usage: 內存占用情況

  Increment: 執行該行代碼后新增的內存

 

使用方法二:

  1.先導入:    from memory_profiler import profile

       2.函數前加裝飾器:   @profile(precision=4,stream=open('memory_profiler.log','w+'))            

            參數含義:precision:精確到小數點后幾位 

                 stream:此模塊分析結果保存到 'memory_profiler.log' 日志文件。如果沒有此參數,分析結果會在控制台輸出

  運行方式:直接跑此腳本  python memory_profiler_test.py

  此方法優點:解決第一種方法的缺點,在 不需要 分析時,直接注釋掉此行

 1 #coding:utf8
 2 from memory_profiler import profile
 3 
 4 @profile(precision=4,stream=open('memory_profiler.log','w+'))
 5 # @profile
 6 def test1():
 7     c=0
 8     for item in xrange(100000):
 9         c+=1
10     print c
11 
12 if __name__=='__main__':
13     test1()

 

使用方法三:

  腳本代碼和方法二一樣,但是 運行方式不同

  mprof run memory_profiler_test.py       : 分析結果會保存到一個 .dat格式文件中

  mprof plot                                              : 把結果以圖片到方式顯示出來(直接在本目錄下運行此命令即可,程序會自動找出.dat文件) (要安裝  pip install matplotlib

       mprof clean                                           : 清空所有 .dat文件

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM