#/usr/bin/perl

# Usage: dotime repeat command

die "Usage: $0 <repeat> <command>\n" if @ARGV < 2;

$repeat = shift(@ARGV);
die "invalid repeat: $repeat, stopped" 
  unless (($repeat > 0) && ($repeat < 999));

# Init our accumulators.

$tt_real = $tt_user = $tt_sys = 0;
@t_real  = @t_user  = @t_sys  = ();

# Now do the timing runs.

print qq/Running "@ARGV" /;
$| = 1;

for $pass (1 .. $repeat) {

    print "$pass ";

    open (TIMES, "/bin/time @ARGV 2>&1 |")
	|| die ("Can't run /bin/time @ARGV: $!\n");

    while (<TIMES>) {
	if (/^real\s+(\d+\.\d+)\n/) {
	    push (@t_real, $1);         # AT&T style
	    $tt_real += $1;
	}
	elsif (/^user\s+(\d+\.\d+)/) {
	    push (@t_user, $1);
	    $tt_user += $1;
	}
	elsif (/^sys\s+(\d+\.\d+)/) {
	    push (@t_sys , $1);
	    $tt_sys += $1;
	}
	elsif (/^\s*(\S+) real\s*(\S+) user\s*(\S+) sys/) {
	    push (@t_real , $1);        # BSD style
	    $tt_real += $1;
	    push (@t_user , $2);
	    $tt_user += $2;
	    push (@t_sys , $3);
	    $tt_sys += $3;
	}
    }
    close (TIMES);
}

print " done\n\n";

# Build a dynamic format.

$fields = '@>>>>>' x $repeat;
$values = ',shift @_' x $repeat;

$form = <<EOFORM;
format STDOUT =
\@<<<\@>>>>>$fields
\$arg,\$avg $values
.
EOFORM

print $form if $debugging;
eval $form;

sub write {
    $avg = shift;
    write;
}

# So write the report already.

&write('Avg', 1 .. $repeat);

&write(split(' ', ' -----' x ($repeat+1)));

for $arg ("real","user","sys ") {
    &write(sprintf("%6.1f", eval "\$tt_$arg/$repeat"),
      eval "\@t_$arg");
}