0

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?

1
  • What did you expect to happen ? Commented May 13, 2018 at 13:14

1 Answer 1

2

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))
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.