http://www.perlmonks.org/index.pl?node_id=187786

Description: Someone on a maillist needed something that would
display the cpu-usage of just 1 or a few pids in a small
xterm. He didn't want to look at top, just 1 line of info.
If you know how to make this better, let me know.
#!/usr/bin/perl                                                       
+                    
use warnings;                                                         
+                    
use strict;                                                           
+                    
use Proc::ProcessTable;                                               
+                    
#usage: cpusage pid1 pid2 pid3.....                                   
+                    
#run without args to get full list                                    
+                    
#then run with chosen pids and it will update                         
+                    
#every 5 secs. No output with invalid pids.                           
+                    
my @pids=undef;                                                       
+                    
my $t = new Proc::ProcessTable;                                       
+                    
@pids = @ARGV;  #get pids to watch on commandline                     
+                    
                                                                      
+                    
if (@pids){                                                           
+                    
while(1){                                                             
+                    
foreach my $p (@{$t->table}) {                                        
+                    
  if(grep {$p->pid == $_}@pids){                                      
+                    
    print "--------------------------------\n";                       
+                    
    print 'pid ',$p->pid,' ',$p->cmndline,' ','CPU% ',$p->{pctcpu},"\n
+";                  
}                                                                     
+                    
}                                                                     
+                    
sleep(5);                                                             
+                    
}                                                                     
+                    
}else{                                                                
+                    
foreach my $p (@{$t->table}) {                                        
+                    
print "--------------------------------\n";                           
+                    
print 'pid ',$p->pid,' ',$p->cmndline,' ','CPU% ',$p->{pctcpu},"\n";  
+                    
}                                                                     
+                    
}                                                                     
+                    
exit(0);    
comment on cpu-usage-by-pid
Download Code

Back to Snippets Section