首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用psutil捕获进程的峰值内存和CPU利用率

如何使用psutil捕获进程的峰值内存和CPU利用率
EN

Stack Overflow用户
提问于 2020-03-31 09:35:18
回答 1查看 1.4K关注 0票数 0

过程P1

代码语言:javascript
复制
#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()

Process P2:

代码语言:javascript
复制
#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’
  2. 的CPU利用率是什么每个子进程'sub.py'

的内存利用率

EN

回答 1

Stack Overflow用户

发布于 2020-04-07 07:50:26

通过大量的搜索时间和精力,我发现获得子进程资源利用率分析是可能的。

更新后的流程P2如下:

代码语言:javascript
复制
# 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))
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60947460

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档