Как зафиксировать пиковое использование памяти и ЦП процесса с помощью psutil - PullRequest
0 голосов
/ 31 марта 2020

Процесс P1 :

#sub.py
#Find the sum of two numbers

def sum_ab(a,b):
    return a+b

def main():
    print(sum_ab(3,6))

if __name__ == '__main__':
    main()

Процесс P2:

#run.py
#Execute sub.py 10 times
import psutil as ps

cmd = ["python3", "sub.py"]

for i in range(10):
    process = ps.Popen(cmd)

Выше приведен сценарий, с которым я работаю. Мне нужно найти процессор и использование памяти каждого из подпроцессов, вызываемых скриптом run.py. Может ли кто-нибудь помочь мне получить информацию о ресурсах процессов RUNNING. Как получить следующее в python.

  1. Что такое загрузка ЦП каждым подпроцессом 'sub.py'
  2. Что такое использование памяти каждым подпроцессом? .py '

1 Ответ

0 голосов
/ 07 апреля 2020

Потратив немного времени и усилий на поиск, я обнаружил, что можно получить анализ использования ресурсов подпроцесса.

Обновленный процесс P2 выглядит следующим образом:

# run.py
# Execute sub.py 10 times

# Import the required utilities
import psutil as ps
import time
from subprocess import PIPE

# define the command for the subprocess
cmd = ["python3", "sub.py"]

for i in range(10):
    # Create the process
    process = ps.Popen(cmd, stdout=PIPE)

    peak_mem = 0
    peak_cpu = 0

    # while the process is running calculate resource utilization.
    while(process.is_running()):
        # set the sleep time to monitor at an interval of every second.
        time.sleep(1)

        # capture the memory and cpu utilization at an instance
        mem = process.memory_info().rss/ (float)(2**30)
        cpu = process.cpu_percent()

        # track the peak utilization of the process
        if mem > peak_mem:
            peak_mem = mem
        if cpu > peak_cpu:
            peak_cpu = cpu
        if mem == 0.0:
            break

    # Print the results to the monitor for each subprocess run.
    print("Peak memory usage for the iteration {} is {} GB".format(i, peak_mem))
    print("Peak CPU utilization for the iteration {} is {} %".format(i, peak_cpu))
...