-
-
Save waryas/f8bba02c8e8358c9fbbc1ce44beeb6d2 to your computer and use it in GitHub Desktop.
Calculating CPU Usage from /proc/stat in Perl
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/perl | |
# Ref: Calculating CPU Usage from /proc/stat | |
# (http://colby.id.au/node/39) | |
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