Skip to content

Instantly share code, notes, and snippets.

@creaktive
Created January 15, 2011 20:58
Show Gist options
  • Save creaktive/781248 to your computer and use it in GitHub Desktop.
Save creaktive/781248 to your computer and use it in GitHub Desktop.
Calculating CPU Usage from /proc/stat in Perl
#!/usr/bin/perl
# Ref: Calculating CPU Usage from /proc/stat
# (http://colby.id.au/node/39)
use strict;
use warnings 'all';
use utf8;
use List::Util qw(sum);
$| = 1;
my ($prev_idle, $prev_total) = qw(0 0);
while () {
open(STAT, '/proc/stat') or die "WTF: $!";
while (<STAT>) {
next unless /^cpu\s+[0-9]+/;
my @cpu = split /\s+/, $_;
shift @cpu;
my $idle = $cpu[3];
my $total = sum(@cpu);
my $diff_idle = $idle - $prev_idle;
my $diff_total = $total - $prev_total;
my $diff_usage = 100 * ($diff_total - $diff_idle) / $diff_total;
$prev_idle = $idle;
$prev_total = $total;
printf "CPU: %0.2f%% \r", $diff_usage;
}
close STAT;
sleep 1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment