In the function shown below, I want to clear the value of x from memory after using it.
def f(x, *args):
# do something
y = g(x) # here i want to use x as argument and clear value of x from ram
# do something
I have tried following method and checked memory usage using memory_profiler but nothing worked:
del xx = None
Sample code on which I tried:
%%file temp.py
import lorem
@profile
def f(x, use_none=True):
# do something
y = g(x)
if use_none:
x = None
else:
del x
# do something
def g(x):
n = len(x)
return [lorem.paragraph() * i for i in range(n)]
if __name__ == '__main__':
x = g([1] * 1000)
# f(x, True)
f(x, False)
memory_profiler command:
python -m memory_profiler temp.py
Result (using None):
Filename: temp.py
Line # Mem usage Increment Line Contents
================================================
3 187.387 MiB 187.387 MiB @profile
4 def f(x, use_none=True):
5 # do something
6 340.527 MiB 153.141 MiB y = g(x)
7 340.527 MiB 0.000 MiB if use_none:
8 340.527 MiB 0.000 MiB x = None
9 else:
10 del x
Result (using del):
Filename: temp.py
Line # Mem usage Increment Line Contents
================================================
3 186.723 MiB 186.723 MiB @profile
4 def f(x, use_none=True):
5 # do something
6 338.832 MiB 152.109 MiB y = g(x)
7 338.832 MiB 0.000 MiB if use_none:
8 x = None
9 else:
10 338.832 MiB 0.000 MiB del x
Edit Deleting from global and gc.collect() is not working
Filename: temp.py
Line # Mem usage Increment Line Contents
================================================
4 188.953 MiB 188.953 MiB @profile
5 def f(x, use_none=True):
6 # do something
7 342.352 MiB 153.398 MiB y = g(x)
8 342.352 MiB 0.000 MiB if use_none:
9 x = None
10 globals()['x'] = None
11 gc.collect()
12 else:
13 342.352 MiB 0.000 MiB del x
14 342.352 MiB 0.000 MiB del globals()['x']
15 342.352 MiB 0.000 MiB gc.collect()
Also, I write this code just for reference, In my actual code, I am calling from function to another function multiple time, and sometimes call same function from inside, based on some parameter value and value of x after some operation.
After every call, I want to delete x after some operation.