Skip to content

Instantly share code, notes, and snippets.

@fskale
Created August 3, 2018 09:15
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 fskale/253b63235a849f78e430f569fb69574b to your computer and use it in GitHub Desktop.
Save fskale/253b63235a849f78e430f569fb69574b to your computer and use it in GitHub Desktop.
Non Blocking CPU Stats (1s) using Mojo::IOLoop:Delay
#!/usr/bin/env perl
use Mojo::Base -strict;
use Mojo::File 'path';
use Mojo::Collection 'c';
use Mojo::IOLoop;
use Mojo::JSON 'j';
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;
}
sub get_stats {
my $file = q{/proc/stat};
my $prev_total = 0;
my $prev_stat = c();
my $out = c();
my $stats = sub {
my $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{%} );
}
);
$prev_stat = $collection;
$prev_total = $total;
};
my $delay = Mojo::IOLoop::Delay->new;
$delay->steps(
sub {
my $delay = shift;
my $end = $delay->begin;
$stats->();
$end->();
},
sub {
my $delay = shift;
Mojo::IOLoop->timer( 1 => $delay->begin );
},
sub {
my $delay = shift;
my $end = $delay->begin;
$stats->();
$end->();
},
sub {
my ( $delay, @args ) = @_;
my $cpu_info->{cpu_info} = {};
my $out_c = c(qw(huser nice sys idle iowait irq softirq steal guest guest_nice));
$out_c->each(
sub {
my ( $value, $key ) = @_;
$cpu_info->{cpu_info}->{$value} = $out->[ $key - 1 ];
}
);
printf( "%s", j($cpu_info) );
}
)->wait;
}
get_stats;
1;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment