Auto Purge Memory in Mac OS X

Attached is a python script that shows all of you memory’s stated

showmemory.py

Here is the code

#!/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 )

We can use a bash onliner to find just Inactive ram on the machine, as this is what we are interested in

vm_stat | awk '/inactive/ {print int($3*4/1024)}'

We could use this in a script, launched by Launcd to check at regular intervals and purge inactive memory if over, for example, 500 MB

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#!/bin/bash

MM=`vm_stat | awk '/inactive/ {print int($3*4/1024)}'`

echo "Testing status of inactive free memory..."

if [ "$MM" -gt "500" ]; then
    echo "You have too much inactive free memory." $MM"MB Releasing now..."
    purge
    exit 0
else
    echo "Memory ammount" $MM"MB does not meet purge threshold."
    exit 0
fi