#!/usr/bin/env python3 # -*- encoding: utf-8 -*- import subprocess as sp import sys import time def get_mem(pid): c = sp.Popen(['ps', '-aux'], stdout=sp.PIPE).stdout.read().decode().split('\n') for line in c: sps = [i for i in line.split(' ') if i] if len(sps) > 1 and pid == sps[1]: if 'Z' in sps[7]: return # 子进程结束 mm = sps[5] return int(mm) cmd = sys.argv[1:] max_mem = -1 p = sp.Popen(cmd, stdout=sp.PIPE) pd = str(p.pid) st = time.time() # print(pd) start_wait = 2 - 1 try: while True: cur_mem = get_mem(pd) if start_wait: start_wait -= 1 if cur_mem is None: if not start_wait: raise KeyboardInterrupt # 进程结束 time.sleep(1) continue max_mem = max(max_mem, cur_mem) print('\rMax memory:'+str(round(max_mem/1024, 2))+' MB', end='') time.sleep(1) except KeyboardInterrupt: print() # sp.Popen(['kill', pd]) # 防止中断后子进程仍然进行 print('用时:', str(round(time.time() - st, 2)), 's')
示例(bash):
# 保存为"mt"(意即memory time);先修改权限为可执行,方便后续调用 chmod 755 mt # 运行 mt sleep 3
标签:linux,sps,程序运行,start,Python,max,sp,mem,time From: https://www.cnblogs.com/roundfish/p/17191988.html