Ruby sort ps
From EggeWiki
Today I needed to sort ps by the total CPU time. I also wanted to sum all the same type processes together. Here's the script I came up with
#!/bin/env ruby # # Given the output from 'ps -o user,time,nlwp,fname' this script will sum the CPU time # header = nil procs = {} procs.default = 0 while((line = STDIN.gets)) f = line.chomp.split(' ') if !header then header = f TIME = f.rindex('TIME') CMD = f.rindex('CMD') || f.rindex('COMMAND') else time = f[TIME].split(':') seconds = time[0].to_i * 60 + time[1].to_i cmd = f[CMD] procs[cmd] += seconds end end sum = 0.0 procs.each { |k,v| sum += v } sorted = procs.sort { |a,b| b[1]<=>a[1] } sorted.each do |k| puts sprintf("%-10s %5.2f%%", k[0], (k[1] / sum) * 100.0) end
Here's a sample of it's usage:
$ ps -A -o user,time,nlwp,fname | ./sumcputime.rb | head java 27.19% dataserv 20.10% Xvnc 7.21% view_ser 4.06% backupse 3.86% httpd 3.64% nscd 2.81% omniName 2.38% se.sparc 2.34% compute_ 2.10%


