I want to use memory_profiler package to analyze memory usage.
However, I've some confusions:
Example 1
# test1.py
from memory_profiler import profile
class Object:
def __init__(self):
pass
list = []
@profile
def func():
for i in range(100000):
list.append(Object())
func()
Results 1
First test
mprof: Sampling memory every 0.1s
running new process
running as a Python program...
Filename: test1.py
Line # Mem usage Increment Occurrences Line Contents
=============================================================
10 43.9 MiB 43.9 MiB 1 @profile
11 def func():
12 50.1 MiB 0.0 MiB 100001 for i in range(100000):
13 50.1 MiB 6.2 MiB 100000 l.append(Object())
Second test
mprof: Sampling memory every 0.1s
running new process
running as a Python program...
Filename: test1.py
Line # Mem usage Increment Occurrences Line Contents
=============================================================
10 44.2 MiB 44.2 MiB 1 @profile
11 def func():
12 50.3 MiB -2867.4 MiB 100001 for i in range(100000):
13 50.3 MiB -2861.3 MiB 100000 l.append(Object())
Question 1
About test1.py:
- The result of memory usage is different some time.
- Are there have memory leak in this example? I think python have garbage collection mechanism, so
listshould beNonewhich will not cause memory leak. However, the result ofmprof plotshow usage increase.
Example 2
# test2.py
from memory_profiler import profile
class Object:
def __init__(self):
pass
@profile
def func():
global list
list = []
for i in range(100000):
list.append(Object())
func()
Results 2
mprof: Sampling memory every 0.1s
running new process
running as a Python program...
Filename: test2.py
Line # Mem usage Increment Occurrences Line Contents
=============================================================
7 44.2 MiB 44.2 MiB 1 @profile
8 def func():
9 global l
10 44.2 MiB 0.0 MiB 1 l = []
11 50.3 MiB -2905.3 MiB 100001 for i in range(100000):
12 50.3 MiB -2899.2 MiB 100000 l.append(Object())
Question 2
About test2.py:
- I think this example will cause a memory leak. The reason is that after the function ends,
listas a global variable still holds a reference to the list, and the objects in the list are not released, resulting in a memory leak. - But why the result of
Incrementwas-2899.2 MiBwhich seem there are not happend memory leak.


