2014-09-22 32 views
0

考慮這兩個代碼,我在Python控制檯運行:Python3.4內存使用

l=[] 
for i in range(0,1000): l.append("."*1000000) 
# if you check your taskmanager now, python is using nearly 900MB 
del l 
# now python3 immediately free-d the memory 

現在考慮這個:

l=[] 
for i in range(0,1000): l.append("."*1000000) 
l.append(l) 
# if you check your taskmanager now, python is using nearly 900MB 
del l 
# now python3 won't free the memory 

因爲我與這些類型的對象的工作,和我需要將它們從我的內存中釋放出來,我需要知道爲了讓python認識到它需要刪除相應的內存。

PS:我正在使用Windows7。

回答

1

因爲您已經創建了一個循環引用,所以內存不會被釋放,直到垃圾收集器運行,檢測到循環並清除它。 You can trigger that manually

import gc 
gc.collect() # Memory usage will drop once you run this. 

集電極將自動運行偶爾,但僅當certain conditions related to the number of object allocations/deallocations are met

gc.set_threshold(threshold0 [,閾值1 [,閾值2]])

設置垃圾收集閾值(收集頻率)。 將threshold0設置爲零將禁用收集。

GC將對象分爲三代,具體取決於它們存活的收集掃描數量。新對象被放置在 最年輕一代(0代)。如果一個物體存活了一個集合 它將被移動到下一代老一代。由於第2代是最古老的一代,因此該代中的對象在收集後保留在那裏。 爲了決定何時運行,收集器保持自從上一次 收集以來對號碼對象分配和釋放的 的跟蹤。當分配數量減去釋放次數 超過閾值0時,收集開始。

所以如果你繼續在解釋器中創建更多的對象,垃圾收集器最終會自行啓動。您可以通過降低threshold0來更頻繁地發生這種情況,或者當您知道刪除了包含參考週期的某個對象時,可以手動調用gc.collect