Thursday, April 1, 2021

Find Max Memory, CPU% of a Subprocess in Python

This program uses psutil to track a job



import atexit

import math

import psutil

import time



cmd = './fib.py' #the script which we will track memory and cpu. It is a simple fibonace series printing program here without any print statement. It can be anything 

child_process = psutil.Popen(cmd, shell=True)


def kill_job():

    if child_process.is_running():

        child_process.kill()

        #child_process.kill


def convert_size(size_bytes):

   if size_bytes == 0:

       return "0B"

   size_name = ("B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB")

   i = int(math.floor(math.log(size_bytes, 1024)))

   p = math.pow(1024, i)

   s = round(size_bytes / p, 2)

   return "%s %s" % (s, size_name[i])


atexit.register(kill_job)


print('PID=', child_process.pid)


counter = 0

max_memory = 0

while 1:

    child_process.poll()

    if child_process.is_running():

        cpu_percentage = child_process.cpu_percent(interval=1)

        cpu_times = child_process.cpu_times()

        memory = child_process.memory_full_info().rss #RES stands for the resident size, which is an accurate representation of how much actual physical memory a process is consuming.

        print('cpu_percentage', cpu_percentage)

        print('cpu_times', cpu_times)

        max_memory = max(memory, max_memory)

        print('memory', memory)

    else:

        print('not running')

        break

    counter += 1

    if counter > 5:

        kill_job()

    time.sleep(1)


print(max_memory)

UA-39217154-2