1. 程式人生 > >計算程序的內存和占比

計算程序的內存和占比

程序 odin main pre == ret 內存占用 put 列表

 1 #!/usr/bin/env python
 2 # _*_ coding:UTF-8 _*_
 3 # 收集程序所占用的物理內存大小,占所有物理內存的比例
 4 # OS: Centos 6.7  Python: 2.7.6 
 5 # __author__:Dahlhin
 6 
 7 import sys
 8 import os
 9 from subprocess import Popen,PIPE
10 
11 def get_pid(program):
12     獲取目標程序的PID列表
13     p = Popen([pidof,program],stdout=PIPE,stderr=PIPE)
14 pids,stderrput = p.communicate() 15 # pids = p.stdout.read() #這種方法也是可以的 16 # 這裏也可以對stderrput來進行判斷 17 if pids: 18 return pids.split() 19 else: 20 raise ValueError 21 22 def mem_calc(pids): 23 計算PIDs占用的內存大小 24 mem_total = 0 25 for pid in pids: 26 os.chdir(
/proc/%s % pid) 27 with open(status) as fd: 28 for line in fd: 29 if line.startswith(VmRSS): 30 mem = line.strip().split()[1] 31 mem_total += int(mem) 32 break 33 return mem_total 34 35 36 def mem_percent(mem):
37 計算程序內存占用物理內存的百分比 38 with open(/proc/meminfo) as fd: 39 for line in fd: 40 if line.startswith(MemTotal): 41 total = line.strip().split()[1] 42 percent = (float(mem)/int(total)) * 100 43 return percent 44 45 46 def main(): 47 try: 48 program = sys.argv[1] 49 pids = get_pid(program) 50 except IndexError as e: 51 sys.exit(%s need a Program name % __file__) 52 except ValueError as e: 53 sys.exit(%s not a Process Name or not Start % program ) 54 mem_total = mem_calc(pids) 55 percent = mem_percent(mem_total) 56 return program,mem_total,percent 57 58 if __name__ == __main__: 59 program,mem_total,mem_percent=main() 60 print(進程名稱:%s\n物理內存為:%s\n百分比為:%.2f%%% (program,mem_total,mem_percent))

計算程序的內存和占比