Mansumen
Mansumen

Reputation: 383

Python memory profile using psutil

I am trying to use psutil to measure the memory usage. However, I found a strange behavior that even if I don't store or load anything, I see that memory usage is keep increasing in a nested for loop. For example, if I run the following code,

import os
import psutil
for i in range(10):
    print(i)
    for j in range(5):
        mem_usage = psutil.Process(os.getpid()).memory_info()[0] / 2 ** 20
        print("{}{} MB".format(j,mem_usage))

I get the following output

0
0178 MB
1178 MB
2178 MB
3178 MB
4178 MB
1
0178 MB
1178 MB
2178 MB
3178 MB
4178 MB

What is going on here?

Is psutil not doing what I intend to do?

Upvotes: 0

Views: 1990

Answers (1)

Giampaolo Rodolà
Giampaolo Rodolà

Reputation: 13066

It's the formatting of your string which is not correct:

"{}{} MB".format(j,mem_usage)

There is no space between "j" and "mem_usage" so it looks like the memory increases when it's not. Also, your math to calculate MB is not correct. It should be:

import os
import psutil

p = psutil.Process(os.getpid())
for i in range(10):
    print(i)
    for j in range(5):
        mem_usage = p.memory_info().rss / 1024 / 1024
        print("{} {} MB".format(j, mem_usage))

Upvotes: 2

Related Questions