Skip to content

Instantly share code, notes, and snippets.

@kazeburo
Created October 26, 2010 06:06
Show Gist options
  • Save kazeburo/646412 to your computer and use it in GitHub Desktop.
Save kazeburo/646412 to your computer and use it in GitHub Desktop.
#!/usr/bin/perl
use strict;
use warnings;
use AnyEvent;
use AnyEvent::Socket;
use AnyEvent::Handle;
use List::Util qw/max sum/;
use Getopt::Long;
# httpd.conf
# CustomLog "|/path/to/apachelatency.pl --port 10456 --interval 300" "%D"
#
# $ telnet localhost 10456
# max=7&avg=2
GetOptions(
'port|p=i' => \my $port,
'interval=i' => \my $interval,
);
$port ||= 10456;
$interval ||= 300;
my @rt;
my $rtavg;
my $rtmax;
my $cv = AE::cv;
tcp_server undef, $port, sub {
my ($fh) = @_;
my $avg = defined $rtavg ? $rtavg : "";
my $max = defined $rtmax ? $rtmax : "";
syswrite $fh, "max=$max&avg=$avg\015\012";
};
my $prev_calc = int( time / $interval );
my $calctimer = AE::timer 0, 1, sub {
if ( $prev_calc != int( time / $interval ) ) {
if ( @rt ) {
$rtmax = max(@rt);
$rtmax = int($rtmax / 1000);
$rtavg = sum(@rt) / scalar @rt;
$rtavg = int($rtavg / 1000);
}
else {
$rtmax = undef;
$rtavg = undef;
}
$prev_calc = int( time / $interval );
@rt = ();
}
};
my $w = AnyEvent::Handle->new(
fh => \*STDIN,
on_eof => sub { $cv->send },
on_error => sub { $cv->send },
);
my $t;
my $read_stdin; $read_stdin = sub {
$w->push_read( line => sub {
my $rt = $_[1];
push @rt, $rt*1;
$t = AE::timer 0, 0, $read_stdin;
});
};
$t = AE::timer 0, 0, $read_stdin;
$cv->recv;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment