Submit Hint Search The Forums LinksStatsPollsHeadlinesRSS
14,000 hints and counting!


Click here to return to the 'Does not work correctly' hint
The following comments are owned by whoever posted them. This site is not responsible for what they say.
Does not work correctly
Authored by: Eravau on Jul 08, '04 06:50:12PM
To get around the "top always being the process hog" problem, I have my script run top with two samples. By the second sample, top has generally calmed down a little and isn't being the processor hog that it always is on launch. My script spits out the Uptime, Current Load Average, Total CPU Use (user + system), and the current CPU Hog Process. Take it and modify to taste:

#!/usr/bin/perl

$top_cmd     = "top -o cpu -l 2 -s 3 -n 1";
$uptime_cmd  = "uptime";
@top         = `$top_cmd`;
$uptime      = `$uptime_cmd`;

$count = scalar @top;

foreach $line_no (10..$count) {
        $line     = $top[$line_no];
        if ($line =~ /Load Avg.\s+(\d+\.\d+)\,\s+(\d+\.\d+)\,\s+(\d+\.\d+)\s+CPU usage.\s+(\d+\.\d+)\% user,\s+(\d+\.\d+)\% sys,\s+(\d+\.\d+)\% idle/) {
                $load_avg = $1;
                $load_rec = $2;
                $load_now = $3;
                $cpu_usr  = $4;
                $cpu_sys  = $5;
                $cpu_idl  = $6;
                $cpu_use  = $cpu_usr + $cpu_sys;
        }
        elsif ($line =~ /PID/) {
                $find_hog = 1;
        }
        elsif ($find_hog) {
                if ($line =~ /\s?\d+\s+(\S+(\s\S+)?)\s+(\d+.\d+)\S\s+\d+.\d\d.\d+/) {
                        $cpu_hog_name = $1;
                        $cpu_hog_prct = $3;
                }
        }
}
if ($uptime =~ /up\s+(\d+)\sday[s]?.\s+(\d+).(\d\d).\s+\d\susers/) {
        $days_up      = $1;
        $hours_up     = $2;
        $mins_up      = $3;
        $formatted_up = $days_up . "d:" . $hours_up . "h:" . $mins_up . "m";
}

print "Up Time:         $formatted_up\n";
print "Current Load:    $load_now\n";
print "Total CPU Use:   $cpu_use\%\n";
print "CPU Hog Process: $cpu_hog_name \@ $cpu_hog_prct\%\n";

exit;
There are a few other variables in there if you'd like to pull those out and display them as well. I just didn't really want to see them myself.

[ Reply to This | # ]