Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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