Algorithm-EventsPerSecond

 view release on metacpan or  search on metacpan

lib/Algorithm/EventsPerSecond.pm  view on Meta::CPAN

	$self->{total} += $count;

	return $self;
} ## end sub _mark_pp

sub _mark_xs {
	my ( $self, $count ) = @_;
	if ( defined $count ) {
		die "count must be a non-negative integer" unless $count =~ /^\d+$/;
	} else {
		$count = 1;
	}

	Algorithm::EventsPerSecond::XS::_xs_mark( $self->{buckets}, $self->{stamps},
		$self->{window}, int( time() ), $count, );
	$self->{total} += $count;

	return $self;
} ## end sub _mark_xs

=head2 count

Number of events recorded within the current window.

=cut

sub _count_pp {
	my ($self) = @_;

	my $now_sec = int( time() );
	my $window  = $self->{window};
	my $oldest  = $now_sec - $window + 1;

	my $sum = 0;
	for my $i ( 0 .. $window - 1 ) {
		$sum += $self->{buckets}[$i]
			if $self->{stamps}[$i] >= $oldest;
	}
	return $sum;
} ## end sub _count_pp

sub _count_xs {
	my ($self) = @_;

	my $now_sec = int( time() );
	return Algorithm::EventsPerSecond::XS::_xs_count( $self->{buckets}, $self->{stamps},
		$self->{window}, $now_sec - $self->{window} + 1,
	);
}

if ( $BACKEND eq 'XS' ) {
	*mark  = \&_mark_xs;
	*count = \&_count_xs;
} else {
	*mark  = \&_mark_pp;
	*count = \&_count_pp;
}

=head2 rate

Average events per second over the window. If the meter has been alive
for less time than the window, the elapsed lifetime is used instead, so
early readings are not artificially deflated.

=cut

sub rate {
	my ($self) = @_;

	my $elapsed = time() - $self->{started};
	my $span    = $elapsed < $self->{window} ? $elapsed : $self->{window};
	return 0 if $span <= 0;

	return $self->count / $span;
}

=head2 total

Lifetime count of all events ever recorded, regardless of window.

=cut

sub total { $_[0]->{total} }

=head2 window

The configured window length in seconds.

=cut

sub window { $_[0]->{window} }

=head2 reset

Clear all counts and restart the clock. Returns the meter object.

=cut

sub reset {
	my ($self) = @_;
	if ( $BACKEND eq 'XS' ) {
		$self->{buckets} = "\0" x ( $self->{window} * 8 );
		$self->{stamps}  = "\0" x ( $self->{window} * 8 );
	} else {
		@{ $self->{buckets} } = (0) x $self->{window};
		@{ $self->{stamps} }  = (0) x $self->{window};
	}
	$self->{total}   = 0;
	$self->{started} = time();
	return $self;
} ## end sub reset

=head2 backend

Returns C<'XS'> when the accelerated backend is in use, C<'PP'> for the
pure Perl fallback. May be called as a class or instance method.

=cut

sub backend { $BACKEND }



( run in 1.586 second using v1.01-cache-2.11-cpan-14f38c9f855 )