Skip to content

Instantly share code, notes, and snippets.

@fskale
Last active July 28, 2018 09:50
Show Gist options
  • Select an option

  • Save fskale/29ab8856c6d981c4c7853f198e76a569 to your computer and use it in GitHub Desktop.

Select an option

Save fskale/29ab8856c6d981c4c7853f198e76a569 to your computer and use it in GitHub Desktop.
CPU Usage percentage summary using Mojolicious Non-blocking IO (EV) feature.
#!/usr/bin/env perl
use Mojo::Base -strict;
use Mojo::File 'path';
use Mojo::Collection 'c';
use Mojo::IOLoop;
BEGIN {
#only linux is supported !
#!linux
die( sprintf( "OS %s not supported !\n", $^O ) ) if $^O ne 'linux';
}
sub read_cpu {
my $file = shift;
my $fh = path($file)->open('r+');
while (<$fh>) {
chomp;
if (/^cpu\s+/) {
( my $content ) = /^cpu\s+(.*)/g;
close($fh) and return c( split( /\s+/, $content ) );
}
else { die( sprintf( "Cannot read stats file %s !\n", $file ) ); }
}
close $fh;
}
my $file = q{/proc/stat};
my $prev_total = 0;
my $prev_stat = c();
Mojo::IOLoop->recurring(
1 => sub {
my ( $out, $collection ) = c();
my $total = 0;
$collection = read_cpu($file);
$collection->map( sub { $total += $_ } );
my $diff_total = $total - $prev_total;
$collection->each(
sub {
my ( $value, $key ) = @_;
$out->[ int($key) - 1 ] = sprintf( "%.1f%s",
( 100 * ( $value - ( $prev_stat->[ int($key) - 1 ] // 0 ) ) / $diff_total ), q{%} );
}
);
printf("\e[1J\e[HUSER\tNICE\tSYS\tIDLE\tIOWAIT\tIRQ\tSOFTIRQ\tSTEAL\tGUEST\tGUEST_NICE\n");
$out->join("\t")->say;
$prev_stat = $collection;
$prev_total = $total;
}
);
Mojo::IOLoop->start unless Mojo::IOLoop->is_running;
1;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment