Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid
 
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);
Replies are listed 'Best First'.
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.

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 about the Monastery: (8)
As of 2016-10-01 18:45 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    How many different varieties (color, size, etc) of socks do you have in your sock drawer?






    Results (5 votes). Check out past polls.