#!/usr/bin/perl -w
use strict;

use constant n => qq[\012];
require LWP::UserAgent;

my($iters)  = 20;
my(@cgis)   = qw( foo.pl bar.pl );
my($lwp)    = {};
my($times)  = {};
my($reqs)   = {};
my($score)  = 0;
my($mult)   = 0;
my($tot)    = 0;
my($i)      = 0;
my($top)    = '';
my($tstr)   = q[qq[iter $iters on $_ was %.5f secs]];

foreach (@cgis) { $$reqs{$_} = HTTP::Request->new('GET', $_) }

foreach (1..$iters) { ++$i; foreach (@cgis) { $$times{$_} += &bench($_) } }

foreach (@cgis) { print(n, sprintf(eval($tstr),$$times{$_})) }


$tot = $$times{$cgis[0]} + $$times{$cgis[1]};

my($faster,$slower) =
   (($$times{$cgis[0]} <=> $$times{$cgis[1]}) < 0)
      ? ($$times{$cgis[0]},$$times{$cgis[1]},&mark([$cgis[0],$cgis[1]]))
      : ($$times{$cgis[1]},$$times{$cgis[0]},&mark([$cgis[1],$cgis[0]]));

$mult    = $slower/$faster;
$faster  = ($faster/$tot)*100;
$slower  = ($slower/$tot)*100;
$score   = ($slower/$faster)*100;

=pod

x TIMES FASTER DISP

   print
      (
         n
         . $$top[0]
         . ' was '
         . sprintf('%.2f',$mult)
         . ' times faster than '
         . $$top[1]
      );
=cut

print
   (
      n.n
         . $$top[0]
         . ' was '
         . sprintf('%.0f',$score)
         . '% faster than '
         . $$top[1] .
      n.n
   );

exit;


sub mark { $top=shift(@_)||$top; $top }

sub bench {

   my($cgi) = shift(@_);
   my($ss)  = 0;
   my($sf)  = 0;

   $lwp = LWP::UserAgent->new('keep_alive'=>0,'timeout'=>5);

   # each new agent get's its own name, so apache knows
   # it's a new client
   $lwp->agent(qq[$cgi $i]);

   $ss = (times)[0]; &bench_apache($$reqs{$cgi}); $sf = (times)[0];

   undef($lwp);

   print(qq[iter $i on $cgi took ].sprintf('%.5f',($sf - $ss)).' secs'.n);

   return($sf-$ss);
}

sub bench_apache { ${\ $lwp->request(shift(@_)) }->status_line() }

BEGIN { ++$| }