« Call Cocoa from ApplescriptApplescript implementations by me »

Keeping an eye on memory

I have 1GB of RAM in my MacBook Pro. Whenever I get a new computer, I immediately upgrade the RAM. 1GB still sounds like a decent amount of RAM to me (must be a throwback to my Performa days) but it gets eat up really quickly. I often run Activity Monitor so that I can keep an eye on my memory usage and kill apps that are causing me to page out. Every time Safari starts eating up my memory, I find that my computer becomes really slow. Apparently page outs are very expensive on a laptop.

Anyway, I like to keep an eye on memory but I hate having to remember it. I resolved this problem today by writing a short python script that ties together a few command line tools. Basically, all you will need is growlnotify since everything else should be installed on a stock Mac.

Here’s the small script that I wrote.

#!/usr/bin/env python

import time, os

def convert(x):
    'Converts the output from awk (received from ps) into a tuple in the following format: (memory_used, name)'
    x = x.strip()
    tmp = x.split(' ')
    tmp[1] = tmp[1].split('/')[-1]
    return int(tmp[0]), tmp[1]

while (True):
    lines = map(convert, os.popen("ps auxww | awk '{ print $6,$11 }'").readlines()[1:])
    for l in lines:
        if l[0] > 100000:
            os.system('growlnotify -a "Activity Monitor" -m "%s is using more than 100MB of memory."' % (l[1]))
    time.sleep(60 * 60) # Update every hour

Save it as something worthwhile (memcheck?), set it to be executable (chmod +x /path/to/memcheck in Terminal.app), and then run it in the background (/path/to/memcheck/ in Terminal.app). Once an hour, you’ll receive a few growl alerts telling you which apps are chewing up memory.

Leave a Reply