我想获取子进程的 CPU 和内存使用情况以进行性能分析。我写了这段代码,但我不知道我输出中的信息是否必要和充分......
import psutil
import time
import subprocess
cmd = "python myScript.py" # for example
start_time = time.time()
proc = psutil.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True)
psProc = psutil.Process(proc.pid)
cpuTime = []
memoryPercent = []
while proc.poll() == None:
cpuTime.append(psProc.cpu_times())
memoryPercent.append(psProc.memory_percent())
time.sleep(1)
execTime = str(time.time() - start_time)
print "\n".join(["execution total time " + execTime, str(max(cpuTime)), "max memory Percent " + str(max(memoryPercent)), "moy memory Percent " + str(sum(memoryPercent)/len(memoryPercent))])
谢谢你的帮助。