in reply to Percent of CPU/Mem Usage for User
Following is fixed code. Should now return data for multiple passed users, and return it in a hash ref, so you can access it by using ${$hash}{users}{username}{cpu}, etc.
Code is a bit cleaned up, but there are many ways I can improve it. Any suggestions are appreciated.
sub userMemCPUpercNidle { my @usernames = @_; my $topcommand = "top -b -n 1 -u "; my $top; # top result my $countusers = 0; my $rethash; foreach my $username (@usernames){ $topcommand .= $username; if ($countusers < $#usernames){ # if there are more users $topcommand .= ", "; } $top = `$topcommand`; # gets top from the system } $top =~ m/(\d+\.\d+)\%id/; # matches CPU idle time $rethash = {'cpuidle' => $1}; # assigns cpu idle to hash $top =~ s/^.+?Swap[^\n]+\s+//s; # removes everything before the proc +esses my @lines = split(/\n/, $top); # split each line into an array value my ($cpucol,$memcol,$usrcol); my $headers = shift(@lines); foreach my $col (split(' ', $headers)){ # determines which collumn e +ach value is in if ($col eq 'USER') { $usrcol = $colcount; # number of col that is the USER val for pr +ocess } elsif ($col eq '%CPU') { $cpucol = $colcount; # number of col that is the CPU val for pro +cess } elsif ($col eq '%MEM') { $memcol = $colcount; # number of col that is the mem val for pro +cess } if (defined($usrcol) && defined($cpucol) && defined($memcol)){ last; } else { $colcount++; } } foreach my $line (@lines){ if (defined($cpucol) && defined($memcol) && defined($usrcol)){ my @values = split(' ', $line); ${$rethash}{users}{$values[$usrcol]}{cpu} += $values[$cpucol]; # + add process cpu percent to total ${$rethash}{users}{$values[$usrcol]}{mem} += $values[$memcol]; # + add process memory percent to total } } return $rethash; }
|
|---|