日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程语言 > python >内容正文

python

python子进程 内存,python中的子进程内存使用情况

發(fā)布時間:2025/4/5 python 25 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python子进程 内存,python中的子进程内存使用情况 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

How can one measure/benchmark maximum memory usage of a subprocess executed within python?

解決方案

I made a little utility class that demonstrates how to do this with the psutil library:

import psutil

import subprocess

class ProcessTimer:

def __init__(self,command):

self.command = command

self.execution_state = False

def execute(self):

self.max_vms_memory = 0

self.max_rss_memory = 0

self.t1 = None

self.t0 = time.time()

self.p = subprocess.Popen(self.command,shell=False)

self.execution_state = True

def poll(self):

if not self.check_execution_state():

return False

self.t1 = time.time()

try:

pp = psutil.Process(self.p.pid)

#obtain a list of the subprocess and all its descendants

descendants = list(pp.get_children(recursive=True))

descendants = descendants + [pp]

rss_memory = 0

vms_memory = 0

#calculate and sum up the memory of the subprocess and all its descendants

for descendant in descendants:

try:

mem_info = descendant.get_memory_info()

rss_memory += mem_info[0]

vms_memory += mem_info[1]

except psutil.error.NoSuchProcess:

#sometimes a subprocess descendant will have terminated between the time

# we obtain a list of descendants, and the time we actually poll this

# descendant's memory usage.

pass

self.max_vms_memory = max(self.max_vms_memory,vms_memory)

self.max_rss_memory = max(self.max_rss_memory,rss_memory)

except psutil.error.NoSuchProcess:

return self.check_execution_state()

return self.check_execution_state()

def is_running(self):

return psutil.pid_exists(self.p.pid) and self.p.poll() == None

def check_execution_state(self):

if not self.execution_state:

return False

if self.is_running():

return True

self.executation_state = False

self.t1 = time.time()

return False

def close(self,kill=False):

try:

pp = psutil.Process(self.p.pid)

if kill:

pp.kill()

else:

pp.terminate()

except psutil.error.NoSuchProcess:

pass

You then use it like so:

import time

#I am executing "make target" here

ptimer = ProcessTimer(['make','target'])

try:

ptimer.execute()

#poll as often as possible; otherwise the subprocess might

# "sneak" in some extra memory usage while you aren't looking

while ptimer.poll():

time.sleep(.5)

finally:

#make sure that we don't leave the process dangling?

ptimer.close()

print 'return code:',ptimer.p.returncode

print 'time:',ptimer.t1 - ptimer.t0

print 'max_vms_memory:',ptimer.max_vms_memory

print 'max_rss_memory:',ptimer.max_rss_memory

總結(jié)

以上是生活随笔為你收集整理的python子进程 内存,python中的子进程内存使用情况的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。