Geeklet: Top RAM Processes

[Tweet : ADN : nvALT]

Top RAM Processes screenshot

This next geeklet is quite similar to the Top CPU Processes geeklet I last shared. It finds the apps and processes with the biggest memory footprint on your system and lists the top 10. The output looks like:

Top RAM processes

WebProcess       926.62M
Mail             360.05M
Safari           211.48M
iTunes           206.38M
Finder           180.80M
Skype            143.15M
WindowServer     137.12M
LaunchBar        135.71M
mds              118.14M
Reeder           117.47M

It includes system-level processes, too, so you can see if something other than your running apps is taking up RAM. Keep in mind that RAM is meant to be used, and having it filled up only starts to slow down your system when it has to page it out constantly. That being said, if your system is slowing down, this overview can give you a quick idea what’s happening.

Here’s the full code. Copy and paste it into a file called memmeter.rb, save it and run chmod a+x /path/to/memmeter.rb. Then set up your shell geeklet to run /path/to/memmeter.rb and you should be good to go.

#!/usr/bin/ruby

def bytesToMeg(bytes)
	if bytes.to_i > (1024*1024)
		bytes = (bytes.to_f/1048576)
		bytes = (bytes * 10**2).round.to_f / 10**2
		bytes = bytes.to_s + '0' if bytes.to_s =~ /\d+\.\d$/
		'  ' + bytes.to_s + 'G'
	else
		bytes = (bytes.to_f/1024)
		bytes = (bytes * 10**2).round.to_f / 10**2
		bytes = bytes.to_s + '0' if bytes.to_s =~ /\d+\.\d$/
		bytes = ' ' + bytes.to_s if bytes.to_s.length == 5
		bytes.to_s + 'M'
	end
end

def spacer(string)
	if string.length > 15
		string = string[0 .. 12] + "  "
	else
		spaces = 16 - string.length
		0.upto(spaces) do
			string += " "
		end
	end
	string
end

input = %x{ps -arcwwwxo "command rss" -m}
counter = 0
total = 0

title = ARGV[0] == "-t" ? ARGV[1] : "Top RAM processes"
print "#{title}\n\n" unless ARGV[0] == "-t" && ARGV[1].nil?

input.split("\n").each {|line|
	if line =~ /^(.*?)\s+(\d{4,})$/
		exit if counter == 5 or total == 10
		puts "#{spacer($1)}#{bytesToMeg($2)}"
		if $2.to_i < 1
			counter += 1
		end
		total += 1
	end
}

Just like the Top CPU Processes script, you can call it with memmeter.rb -t "Title to display", or just -t to display no title. If no parameters are given, it will display “Top RAM Processes.”

Next up, either a good system status overview script or some network status geeklets. Whichever my geek muse picks first, I suppose.