Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"

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");
   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";
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?

What's my password?
Create A New User
Node Status?
node history
Node Type: snippet [id://464330]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others about the Monastery: (11)
As of 2018-01-18 14:43 GMT
Find Nodes?
    Voting Booth?
    How did you see in the new year?

    Results (212 votes). Check out past polls.