I want to measure the RAM usage of each for loop in my code. I searched internet and find process = psutil.Process(os.getpid()) and print(process.memory_info().rss) for measuring RAM. But this code gets the pid of the whole process and not a specific part.
Is there any way to measure RAM usage of each part of the code? For example in code below we have 3 for loops which fill 3 different dictionaries. I want to print RAM usage of each for loop and between the processing of each loop, if the RAM exceed a threshold, i want to break that for loop.
dict1 = {}
dict2 = {}
dict3 = {}
for i in range (200):
do something with dict1
if RAM usage of this block exceeds 1GB then break
this loop used: x Mb
for i in range (500):
do something with dict2
if RAM usage of this block exceeds 1GB then break
this loop used: x2 Mb
for i in range (800):
do something with dict3
if RAM usage of this block exceeds 1GB then break
this loop used: x3 Mb
I appreciate answers which can help me a lot