[英]Python memory_profiler: memory usages does not add up
memory_profiler的文檔提供了一個簡單的示例,該示例顯示了由於創建和刪除列表而導致的內存使用變化。
from memory_profiler import profile
@profile
def my_func():
a = [1] * (10 ** 6)
b = [2] * (2 * 10 ** 7)
del b
return a
if __name__ == '__main__':
my_func()
產生以下輸出:
Line # Mem usage Increment Line Contents
==============================================
3 @profile
4 5.97 MB 0.00 MB def my_func():
5 13.61 MB 7.64 MB a = [1] * (10 ** 6)
6 166.20 MB 152.59 MB b = [2] * (2 * 10 ** 7)
7 13.61 MB -152.59 MB del b
8 13.61 MB 0.00 MB return a
刪除b
,將釋放其內存使用量。 我正在玩耍,並將示例更改為以下示例,其中還刪除a
。
from memory_profiler import profile
@profile
def my_func():
a = [1] * (10 ** 6)
b = [2] * (2 * 10 ** 7)
del a
del b
return None
if __name__ == '__main__':
my_func()
但是,在這里,刪除a
並不會(如我天真地期望的那樣)伴隨內存使用量的減少。 實際上,似乎什么也沒有發生。
Line # Mem usage Increment Line Contents
================================================
12 25.1 MiB 0.0 MiB @profile
13 def my_func():
14 32.7 MiB 7.6 MiB a = [1] * (10 ** 6)
15 185.3 MiB 152.6 MiB b = [2] * (2 * 10 ** 7)
16 185.3 MiB 0.0 MiB del a
17 32.7 MiB -152.6 MiB del b
18 32.7 MiB 0.0 MiB return None
到底是怎么回事?
實際上, del a
並不會刪除該對象,它只是將對象標記為未使用,但是只要垃圾收集器認為合適,它就會在以后刪除。 b
足夠大,可以使垃圾收集器立即將其刪除,但是對於a
來說顯然不是這樣
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.