계산 프로그램의 메모리와 비례

8607 단어
계산 프로그램의 메모리와 비례
 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
:%s
:%.2f%%
'% (program,mem_total,mem_percent))

 
posted @
2017-05-05 12:00 Dahlhin 읽기(
...) 설명(
...) 모음 편집

좋은 웹페이지 즐겨찾기