Skip to content

Instantly share code, notes, and snippets.

@citrin
Created March 7, 2014 13:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save citrin/9411934 to your computer and use it in GitHub Desktop.
Save citrin/9411934 to your computer and use it in GitHub Desktop.
#!/usr/bin/perl
use 5.012;
use warnings;
my @cpu_times = split /\s+/, `sysctl -n kern.cp_times`;
die "xxx" unless @cpu_times;
my $cnt1 = [];
my $cnt2 = [];
my $cur_cpu = 0;
while (@cpu_times) {
$cnt1->[$cur_cpu]->{user} = shift @cpu_times;
$cnt1->[$cur_cpu]->{nice} = shift @cpu_times;
$cnt1->[$cur_cpu]->{sys} = shift @cpu_times;
$cnt1->[$cur_cpu]->{intr} = shift @cpu_times;
$cnt1->[$cur_cpu]->{idle} = shift @cpu_times;
$cnt1->[$cur_cpu]->{total} = $cnt1->[$cur_cpu]->{nice} + $cnt1->[$cur_cpu]->{sys}
+ $cnt1->[$cur_cpu]->{intr} + $cnt1->[$cur_cpu]->{idle};
$cur_cpu++;
}
sleep 15; # to calculate average load for 15 seconds
@cpu_times = split /\s+/, `sysctl -n kern.cp_times`;
die "xxx" unless @cpu_times;
$cur_cpu = 0;
while (@cpu_times) {
$cnt2->[$cur_cpu]->{user} = shift @cpu_times;
$cnt2->[$cur_cpu]->{nice} = shift @cpu_times;
$cnt2->[$cur_cpu]->{sys} = shift @cpu_times;
$cnt2->[$cur_cpu]->{intr} = shift @cpu_times;
$cnt2->[$cur_cpu]->{idle} = shift @cpu_times;
$cnt2->[$cur_cpu]->{total} = $cnt2->[$cur_cpu]->{nice} + $cnt2->[$cur_cpu]->{sys}
+ $cnt2->[$cur_cpu]->{intr} + $cnt2->[$cur_cpu]->{idle};
$cur_cpu++;
}
my $max_cpu = $cur_cpu - 1;
for $cur_cpu (0 .. $max_cpu) {
printf "CPU%d: %.2f idle\n", $cur_cpu,
100 * ($cnt2->[$cur_cpu]->{idle} - $cnt1->[$cur_cpu]->{idle}) / ($cnt2->[$cur_cpu]->{total} - $cnt1->[$cur_cpu]->{total});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment