mac下python实现vmstat

mac下没有linux/unix 的vmstat,只有vm_stat;

sh-3.2# vm_stat
Mach Virtual Memory Statistics: (page size of 4096 bytes)
Pages free: 191876.
Pages active: 433086.
Pages inactive: 141819.
Pages speculative: 23119.
Pages throttled: 0.
Pages wired down: 254606.
Pages purgeable: 11895.
"Translation faults": 20445131.
Pages copy-on-write: 1435992.
Pages zero filled: 10414067.
Pages reactivated: 39459.
Pages purged: 23388.
File-backed pages: 172905.
Anonymous pages: 425119.
Pages stored in compressor: 12595.
Pages occupied by compressor: 3399.
Decompressions: 5824.
Compressions: 26966.
Pageins: 1626450.
Pageouts: 4218.
Swapins: 1487.
Swapouts: 5130.

不想用下面这个复杂top命令

sh-3.2# top -l 1 -s 0 | grep PhysMem
PhysMem: 3277M used (992M wired), 817M unused.

用下面这个python

#!/usr/bin/python

import subprocess
import re

# Get process info
ps = subprocess.Popen(['ps', '-caxm', '-orss,comm'], stdout=subprocess.PIPE).communicate()[0]
vm = subprocess.Popen(['vm_stat'], stdout=subprocess.PIPE).communicate()[0]

# Iterate processes
processLines = ps.split('\n')
sep = re.compile('[\s]+')
rssTotal = 0 # kB
for row in range(1,len(processLines)):
    rowText = processLines[row].strip()
    rowElements = sep.split(rowText)
    try:
        rss = float(rowElements[0]) * 1024
    except:
        rss = 0 # ignore...
    rssTotal += rss

# Process vm_stat
vmLines = vm.split('\n')
sep = re.compile(':[\s]+')
vmStats = {}
for row in range(1,len(vmLines)-2):
    rowText = vmLines[row].strip()
    rowElements = sep.split(rowText)
    vmStats[(rowElements[0])] = int(rowElements[1].strip('\.')) * 4096

print 'Wired Memory:\t\t%d MB' % ( vmStats["Pages wired down"]/1024/1024 )
print 'Active Memory:\t\t%d MB' % ( vmStats["Pages active"]/1024/1024 )
print 'Inactive Memory:\t%d MB' % ( vmStats["Pages inactive"]/1024/1024 )
print 'Free Memory:\t\t%d MB' % ( vmStats["Pages free"]/1024/1024 )
print 'Real Mem Total (ps):\t%.3f MB' % ( rssTotal/1024/1024 )

 sh-3.2# ./mem.py

Wired Memory: 1013 MB
Active Memory: 1951 MB
Inactive Memory: 573 MB
Free Memory: 423 MB
Real Mem Total (ps): 3180.027 MB

posted @ 2015-10-18 13:50  facewater  阅读(1143)  评论(0编辑  收藏  举报