AnyEvent-Monitor-CPU
view release on metacpan or search on metacpan
lib/AnyEvent/Monitor/CPU.pm view on Meta::CPAN
my %stats;
my ($count, $sum);
if ($count = $self->{usage_count}) {
$sum = $self->{usage_sum};
$stats{usage_avg} = $sum/$count;
}
$stats{usage_count} = $count;
$stats{usage_sum} = $sum;
$stats{usage} = $self->{usage};
return \%stats;
}
sub _check_cpu {
my $self = $_[0];
my $chs = $self->{current_high_samples};
my $cls = $self->{current_low_samples};
my $usage = $self->{usage} = $self->{cpu}->usage;
if ($usage > $self->{high}) { $chs++; $cls = 0 }
elsif ($usage < $self->{low}) { $cls++; $chs = 0 }
else {
$chs-- if $chs;
$cls-- if $cls;
}
$self->{usage_sum} += $usage;
$self->{usage_count}++;
my $hs = $self->{high_samples};
my $ls = $self->{low_samples};
my $state = $self->{state};
my $trigger = 0;
if ($chs >= $hs) {
$chs = $hs;
if ($state) {
$state = 0;
$trigger = 1;
}
}
elsif ($cls >= $ls) {
$cls = $ls;
if (!$state) {
$state = 1;
$trigger = 1;
}
}
$self->{state} = $state;
$self->{current_high_samples} = $chs;
$self->{current_low_samples} = $cls;
$self->{cb}->($self, $state) if $trigger;
}
1;
__END__
=encoding utf8
=head1 NAME
AnyEvent::Monitor::CPU - monitors your process CPU usage, with high/low watermark triggers
=head1 VERSION
version 0.3
=head1 SYNOPSIS
use AnyEvent::Monitor::CPU qw( monitor_cpu );
my $monitor = monitor_cpu cb => sub {
my ($self, $on_off_flag) = @_;
# look at $on_off_flag
# * 1: below the low watermak - you can increase your CPU usage
# * 0: above the high watermark - reduce your CPU usage;
}
;
## Or...
use AnyEvent::Monitor::CPU;
my $monitor = AnyEvent::Monitor::CPU->new(
cb => sub { ... }
);
## other goodies
my $last_measured_usage = $monitor->usage;
my $have_spare_cpu = $monitor->is_low;
my $we_are_overloaded = $monitor->is_high;
## stats
use Data::Dump qw(pp);
my $stats = $monitor->stats;
print pp($stats);
# {
# usage_count => 5,
# usage_sum => 3.344552,
# usage_avg => 0.668910,
# usage => 0.540231,
# }
$monitor->reset_stats;
print pp($monitor->stats);
# {
# usage_count => 0,
# usage_sum => 0,
# usage => 0.481203,
# }
## monitor stop/start control
$monitor->stop;
$monitor->start;
$monitor->is_running;
( run in 0.641 second using v1.01-cache-2.11-cpan-39bf76dae61 )