Skip to content

Instantly share code, notes, and snippets.

@chetan
Last active November 5, 2016 16:18
Show Gist options
  • Save chetan/4e78c4d6830ff36ae166614565a18655 to your computer and use it in GitHub Desktop.
Save chetan/4e78c4d6830ff36ae166614565a18655 to your computer and use it in GitHub Desktop.
A little ruby script to show process memory usage grouped by ppid
#!/usr/bin/env ruby
def run!
ps = []
`ps -el`.split(/\n/).each do |line|
# UID PID PPID F CPU PRI NI SZ RSS WCHAN S ADDR TTY TIME CMD
l = line.split("\s")
x = {
:uid => l.shift,
:pid => l.shift,
:ppid => l.shift,
:f => l.shift,
:cpu => l.shift,
:pri => l.shift,
:ni => l.shift,
:vsz => l.shift,
:rss => l.shift,
:wchan => l.shift,
:s => l.shift,
:addr => l.shift,
:tty => l.shift,
:time => l.shift,
:children => []
}
x[:cmd] = l.join(" ")
ps << x
end
ps.shift # get rid of headers
ps.sort!{ |x,y| x[:pid] <=> y[:pid] }.reverse!
ps.each do |x|
next if x[:ppid] == "1" || x[:ppid] == "0"
ps.each do |y|
if y[:pid] == x[:ppid] then
y[:children] << x
end
end
end
ps.delete_if { |x| x[:ppid] != "1" && x[:ppid] != "0" }
ps.reverse!
# dispaly results
ret = []
ps.each do |x|
ret << {
rss: rss(x),
cmd: x[:cmd],
children: x[:children]
}
end
ret.sort!{ |x,y| y[:rss] <=> x[:rss] }
puts "RSS\t\tCHILDREN\tCMD"
ret.each do |x|
puts "#{x[:rss]}\t\t#{x[:children].size}\t\t#{x[:cmd]}"
end
end
def rss(x)
sum = x[:rss].to_i
x[:children].each{ |y| sum += rss(y) }
sum
end
run!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment