ulvis.paste.net

Paste Search Dynamic
Recent pastes
CPU usage
  1. #!/usr/bin/env ruby
  2. #################################################################
  3. ## Name: getcpuram.rb                                          ##
  4. ## Desc: Obtain CPU% or RAM Usage with only the PID of process ##
  5. ## Licence: BSD                                                ##
  6. ## Author: Marc Lagrange <markocpc@gmail.com>                  ##
  7. ## Usage:  CPU%: getcpuram.rb cpu PID                          ##
  8. ##         RAM : getcpuram.rb ram PID                          ##
  9. #################################################################
  10.  
  11. pid = ARGV[1]
  12. type = ARGV[0]
  13.  
  14. def ps_get(type_fnc, pid_fnc)
  15.   if pid_fnc =~ /\A[+-]?\d+\z/
  16.     # its an integer
  17.     if pid_fnc.length > 5
  18.       # PID too big
  19.     else
  20.       # OH ! I'm happy, it's a PID !
  21.       cmd = "ps -p #{pid_fnc.to_s} -o #{type_fnc}="
  22.       res_cmd = %x[#{cmd}]
  23.       if type_fnc == 'rss'
  24.         if res_cmd.empty?
  25.         else
  26.           ram_mb = res_cmd.to_i / 1024
  27.           return ram_mb.to_s
  28.         end
  29.       else
  30.         return res_cmd.strip unless res_cmd.empty?
  31.       end
  32.     end
  33.   else
  34.   end
  35. end
  36.  
  37. case ARGV[0]
  38. when /cpu/i
  39.   # first arg = cpu
  40.   cpu_reply = ps_get('pcpu', pid)
  41.   puts "Cpu: #{cpu_reply}%"
  42.  
  43. when /ram/i
  44.   # first arg = ram
  45.   ram_reply = ps_get('rss', pid)
  46.   ramp_reply = ps_get('pmem', pid)
  47.   puts "Ram: #{ram_reply.strip}MB - #{ramp_reply.strip}%"
  48.  
  49. when /perc/i
  50.   ramp_reply = ps_get('pmem', pid)
  51.   puts ramp_reply.strip
  52.  
  53. when /mb/i
  54.   ram_reply = ps_get('rss', pid)
  55.   puts ram_reply.strip
  56.  
  57. else
  58.   #first arg is PID ?
  59.   cpu_reply = ps_get('pcpu', type)
  60.   ram_reply = ps_get('rss', type)
  61.   ramp_reply = ps_get('pmem', type)
  62.   puts "Cpu: #{cpu_reply.chomp}%, Ram: #{ram_reply.chomp}MB - #{ramp_reply.chomp}"
  63.  
  64. end
Parsed in 0.013 seconds