Ruby sort ps: Difference between revisions

From EggeWiki
(New page: 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 <geshi lang="ruby"> #!/bin/env ruby # # Giv...)
 
mNo edit summary
 
Line 47: Line 47:
</geshi>
</geshi>


[[Category:Ruby]]
[[Category:Ruby|sort ps]]
[[Category:Solaris]]
[[Category:Solaris]]

Latest revision as of 20:41, 30 July 2008

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

<geshi lang="ruby">

  1. !/bin/env ruby
  2. 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 </geshi>

Here's a sample of it's usage: <geshi lang="bash"> $ 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% </geshi>