2011-08-09 34 views
29

我期待從一個大的Python代碼庫中生成一個函數運行過程中堆使用或內存分配的摘要。Python逐行內存分析器?

我對heapy很熟悉,它爲我在代碼中的特定點上拍攝堆的「快照」提供了很好的幫助,但是我發現很難生成「隨時間改變內存」它。我也玩過line_profiler,但是這與運行時間,而不是記憶。

我現在的備忘錄是Valgrind的massif,但缺少很多Heapy和line_profiler給出的上下文Python信息。後兩者是否有某種組合可以在Python程序的執行範圍內給出內存使用或堆增長的感覺?

+0

你可以用http://docs.python.org/devguide/gdb.html來做到嗎,如果你關心的是在C世界中發生的事情? – agf

+0

如果有一種方法可以定期自動運行gdb,那麼C視角就可以了 - 有沒有這樣的方法? – Tim

+1

一個很好的問題,我很想知道,所以我加了一個賞金。 – bgw

回答

13

我會在程序啓動時使用sys.settrace來註冊一個自定義的跟蹤函數。將爲每行代碼調用custom_trace_function。然後,您可以使用該功能將由heapy或meliae收集的信息存儲在文件中供以後處理。

這是一個非常簡單的例子,其記錄hpy.heap的輸出()每一秒,以純文本文件:

import sys 
import time 
import atexit 
from guppy import hpy 

_last_log_time = time.time() 
_logfile = open('logfile.txt', 'w') 

def heapy_profile(frame, event, arg): 
    currtime = time.time() 
    if currtime - _last_log_time < 1: 
     return 
    _last_log_time = currtime 
    code = frame.f_code 
    filename = code.co_filename 
    lineno = code.co_firstlineno 
    idset = hpy().heap() 
    logfile.write('%s %s:%s\n%s\n\n' % (currtime, filename, lineno, idset)) 
    logfile.flush() 

atexit.register(_logfile.close) 
sys.settrace(heapy_profile) 
+1

我還沒有嘗試它*但*看起來我們可能有一個贏家。 (我會等到賞金時期結束時獎勵積分,以防其他人想要嘗試這個問題) – bgw