我有一個運行循環的python腳本。在此循環中,函數DoDebugInfo
被調用,每循環迭代一次。此功能基本上使用matplotlib打印一些圖片到硬盤,導出KML文件並執行一些其他計算,並且什麼都不返回。python循環快速增加其內存使用
我有問題,蟒蛇,每次運行,功能DoDebugInfo
吃越來越多的內存。我想一些變量正在增加每個循環的大小。
print '=== before: ' + str(resource.getrusage(resource.RUSAGE_SELF).ru_maxrss/1000)
DoDebugInfo(inputs)
print '=== after: ' + str(resource.getrusage(resource.RUSAGE_SELF).ru_maxrss/1000)
輸出是:
=== before: 71598.08
=== after: 170237.952
=== before: 170237.952
=== after: 255696.896
=== before: 255696.896
=== after: 341409.792
正如你所看到的,在調用之前的程序有一個內存佔用,經過
我通話之前和之後添加以下行該呼叫增加,但保持穩定,直到下一次呼叫。
這是爲什麼?因爲DoDebugInfo(inputs)
是一個不返回任何內容的函數,怎麼會有一些變量留在內存中?是否需要在函數結束時清除所有變量?
編輯: 的DoDebugInfo
進口此功能:
def plot_line(x,y,kind,lab_x,lab_y,filename):
fig = plt.figure(figsize=(11,6),dpi=300)
ax = fig.add_subplot(111)
ax.grid(True,which='both')
#print 'plotting'
if type(x[0]) is datetime.datetime:
#print 'datetime detected'
ax.plot_date(matplotlib.dates.date2num(x),y,kind)
ax.fmt_xdata = DateFormatter('%H')
ax.autoscale_view()
fig.autofmt_xdate()
else:
#print 'no datetime'
ax.plot(x,y,kind)
xlabel = ax.set_xlabel(lab_x)
ax.set_ylabel(lab_y)
fig.savefig(filename,bbox_extra_artists=[xlabel], bbox_inches='tight')
def plot_hist(x,Nbins,lab_x,lab_y,filename):
fig = plt.figure(figsize=(11,6),dpi=300)
ax = fig.add_subplot(111)
ax.grid(True,which='both')
ax.hist(x,Nbins)
xlabel = ax.set_xlabel(lab_x)
ax.set_ylabel(lab_y)
fig.savefig(filename,bbox_extra_artists=[xlabel], bbox_inches='tight')
和情節使用類似的10個數字磁盤:
plot_line(index,alt,'-','Drive Index','Altitude in m',output_dir + 'name.png')
如果我評論說,使用plot_line
線的問題不發生,所以泄漏應該在這行代碼上。
感謝
向我們展示您的'DoDebugInfo'功能。 – eumiro
不返回任何內容的函數仍然可以改變全局變量,或者使用在調用之間沒有清理的可變參數。 –
@eumiro我已經縮小了泄漏,請看看我在'DoDebugInfo'中使用的函數。這裏是泄漏的地方。謝謝 – otmezger