Perl Script to Get CPU Percent Used

Found this old perl script in my scratch scripts to get the current CPU load on Linux. Perls been replaced with Python for most of my work now but it does job.

#!/usr/bin/perl
# gets cpu seperated by 2 seconds
open(STAT, "</proc/stat");
my ($junk, $cpu_user, $cpu_nice, $cpu_sys, $cpu_idle) = split(/\s+/,<STAT>);
close(STAT);
my $cpu_total1 = $cpu_user + $cpu_nice + $cpu_sys + $cpu_idle;
my $cpu_load1 = $cpu_user + $cpu_nice + $cpu_sys;
sleep 2;
open(STAT,"</proc/stat");
($junk, $cpu_user, $cpu_nice, $cpu_sys, $cpu_idle) = split(/\s+/,<STAT>);
close(STAT);
my $cpu_total2 = $cpu_user + $cpu_nice + $cpu_sys + $cpu_idle;
my $cpu_load2 = $cpu_user + $cpu_nice + $cpu_sys;
my $a = $cpu_load2 - $cpu_load1;
my $b = $cpu_total2 - $cpu_total1;
##printf("CPU Usage: %4.1f\n", 100.0*$a/$b);
printf("%4.1f%", 100.0*$a/$b);

Leave a Reply

Your email address will not be published. Required fields are marked *