http://www.perlmonks.org?node_id=464330

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.