Plopp
Plopp

Reputation: 977

Monitoring subprocess resources over time in python

I'm currently trying to monitor over time the memory usage of my subprocess to generate a plot.

This chunk of code seems to do the trick but I REALLY don't like the "over time" loop I made, as you can see this is a basic while true loop.

from subprocess import Popen
import psutil

process = Popen(["python", "dummy_script.py"])
ps = psutil.Process(process.pid)

while process.poll() is None:
    print(ps.memory_percent())

I'd like to tweak this code to be able to check the memory usage of my subprocess at a fixed interval (1 second for instance).

This is my first time working with both subprocess and psutil so I have some trouble understanding how to do it properly.

Note: here's the dummy_script.py which is not interesting

import numpy
import time

result = []
for i in range(10240):
    result.append(numpy.random.bytes(1024*1024))
print(len(result))

Upvotes: 3

Views: 726

Answers (1)

Kenan
Kenan

Reputation: 14094

Have the program sleep for 1 second in your while loop

import time

while process.poll() is None:
    print(ps.memory_percent())
    time.sleep(1)

Upvotes: 3

Related Questions