Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

Linux CPU usage monitor

by bofh_of_oz (Hermit)
on Jun 07, 2005 at 14:50 UTC ( #464330=snippet: print w/ replies, xml ) Need Help??

Description: The code in the snippet monitors the aggregate CPU usage (user+nice+system, all CPUs) on a Linux system. Can be included in a larger script (that's what I do, to log it to database)

UPDATE: reworked as per merlyn's advice.

use strict;
use warnings;

open(INFIL,"< /proc/stat") or die("Unable To Open /proc/stat: $!\n");
while()
{
   my @loads;
   my $cpuload = 0;
   for (0,1)
   {
      my $in = <INFIL>;
      (warn "something wrong!\n"), next unless $in =~ /^cpu\b/;
      push @loads,  ($in =~ /\d+/g)[0..2];
      seek INFIL, 0, 0;
      select (undef, undef, undef, 1) unless $_;
   }
   redo unless defined $loads[0];
   for (0..2) { $cpuload += ($loads[$_+3] - $loads[$_]); }
   print "$cpuload\n";
}
close(INFIL);
Comment on Linux CPU usage monitor
Download Code
Re: Linux CPU usage monitor
by merlyn (Sage) on Jun 07, 2005 at 15:01 UTC
    <INFIL> =~ /^cpu\s+(\d+)\s+(\d+)\s+(\d+).*/; @loads = ($1, $2, $3);
    You're using $1 without testing whether the match succeeded. Either add "or die" to your matches (if not matching would be an exceptional condition), or put your use of $1 within the context of a conditional statement based on the match success.

    -- Randal L. Schwartz, Perl hacker
    Be sure to read my standard disclaimer if this is a reply.

Back to Snippets Section

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: snippet [id://464330]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others exploiting the Monastery: (7)
As of 2015-07-05 10:37 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (61 votes), past polls