【问题标题】:How to capture the Peak Memory and CPU utilization of the process using psutil如何使用 psutil 捕获进程的峰值内存和 CPU 利用率
【发布时间】:2020-03-31 09:35:18
【问题描述】:

流程 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”脚本调用的每个子进程的 CPU 和内存利用率。谁能帮我推导出正在运行的进程的资源信息。如何在python中导出以下内容。

  1. 每个子进程 'sub.py' 的 CPU 利用率是多少
  2. 每个子进程“sub.py”的内存利用率是多少

【问题讨论】:

    标签: python-3.x memory-management subprocess popen psutil


    【解决方案1】:

    经过一番搜索,发现可以得到子进程资源利用率分析。

    更新后的Process 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))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-09-25
      • 2014-12-01
      • 1970-01-01
      • 2017-05-19
      • 2012-07-16
      • 1970-01-01
      • 2020-03-13
      相关资源
      最近更新 更多