python 计算apache进程占用的内存大小以及占物理内存的比例

 
目的:计算所有apache进程占用的内存大小以及占物理内存的比例:
思路:利用系统中/proc/meminfo的现有数据进行统计
1、pidof列出服务对应进程的PID
[root@yangliheng ~]# pidof httpd
31235 23664 5358 5357 5356 5355 5354 5353 5352 5351 1498

 

2、读取PID对应的文件/proc/5355/status(以PID5355为例),遍历得到这个进程对应的占用内存(VmRSS对应的)
[root@yangliheng ~]# cat /proc/5355/status
Name:httpd
State:S (sleeping)
Tgid:5355
Pid:5355
PPid:1498
VmHWM:   51336 kB
VmRSS:   45720 kB

 

3、查看/proc/meminfo得到系统的总物理内存
4、就算将Apache 对应所有进程的内存相加,与系统总物理内存相比得到所占比例
$cat /proc/meminfo
MemTotal:        2052440 kB //总内存

 



 
#!/usr/bin/env python
import os
from subprocess import Popen, PIPE
def getPid():
    p=Popen(['pidof','httpd'],stdout=PIPE,stderr=PIPE)
    pids = p.stdout.read().split()
    return pids
 
def paresPidFile(pids):
     sum =0
     for i in pids:
         fn = os.path.join('/proc/',i,'status')
         with open(fn) as fd:
            for line in fd:
                 if line.startswith('VmRSS'):
                     http_mem =int(line.split()[1])
                     sum += http_mem
                     break
     return sum
def total_mem(f):
    with open(f) as fd:
        for line in fd:
             if line.startswith('MemTotal'):
                    total_mem =int(line.split()[1])
                    return total_mem
if __name__ =='__main__':
    pids = getPid()
    http_mem = paresPidFile(pids)
    total = total_mem('/proc/meminfo')
    print"Apache memory is: %s KB"% http_mem
    print "Percent: %.2f%%"%(http_mem/float(total)*100)

  

 
 





posted @ 2016-07-21 15:54  杨小愚  阅读(1084)  评论(0编辑  收藏  举报