#!/usr/bin/perl
### hpsum-summary.pl
###
###	this perl script collates the data from hpsum and should only be
###	called from the system call inside the program
###
#

$OUTPUTDIR=".hpsum-${ENV{MP_PARTITION}}";
$NUM_LINES_FOR_TAIL=6;
$SUFFIX=".hpsum";

###
### end customizations
###

open(PIDFILES, "ls -1 ${OUTPUTDIR}/pid.* |") || die("can't get list of pids: $!");
while(<PIDFILES>){
	s/pid\.//;
	chomp;
	push @matches, $_;
}
close PIDFILES;

while(@matches){
	$nextfile = shift @matches;
	while($doneyet ne "--FIN--"){
		open(TAIL, "tail -n 1 ${nextfile} |");
		$doneyet = <TAIL>;
		chomp $doneyet;
		if($doneyet ne "--FIN--") { 
			print "still waiting for --FIN-- from $nextfile, sleeping...";
			close(TAIL);
			sleep 2;
		}
	}
	open(TAIL, "tail -n ${NUM_LINES_FOR_TAIL} ${nextfile} |");
	while(<TAIL>){ if($_ ne "--FIN--\n") { push @results, $_; } }
	close TAIL;
}

while(@results){
	$_ = pop @results;
	($nothing, $entry) = split(/::/, $_, 2);
	($counttype, $total_value, $rel_value) = split(/:/, $entry, 3);

	if(/PM_FPU0_CMPL/) { $fpu0_ops += $total_value; }
	if(/PM_FPU1_CMPL/) { $fpu1_ops += $total_value; }
	if(/PM_BURSTRD_L2MISS/) { $L2misses += $total_value; }
	if(/PM_ST_L2MISS/) { $L2misses += $total_value; }
	if(/PM_TLB_MISS/) { $TLBmisses += $total_value; }
	if(/PM_INST_CMPL/) { $total_insts += $total_value; }
	if(/PM_EXEC_FMA/) { $fp_fma_ops += $total_value; }
	if(/PM_CYC/) { $cycles += $total_value; }
}	

($useconds, $garbage) = split(/:/, $nothing, 2);

$total_fp_ops = $fpu0_ops + $ fpu1_ops;
if(!$useconds){ $useconds = 1; }
$seconds = $useconds/1000.0;
$total_mflops = $total_fp_ops / ($seconds * 1000000);


print "-------------------------------------------------\n";
print "SUMMARY\n";
print "-------------------------------------------------\n";
if($fpu0_ops){ print "$fpu0_ops\t\tFPU0 operations\n"; }
if($fpu1_ops){ print "$fpu1_ops\t\tFPU1 operations\n"; }
if($total_fp_ops){
print "$total_fp_ops\t\tTOTAL fp ops in $seconds seconds ($total_mflops MFLOPS)\n";
}
if($L2misses){ print "$L2misses\t\tL2 cache misses\n"; }
if($TLBmisses){ print "$TLBmisses\t\tTLB cache misses\n"; }
if($total_insts){ print "$total_insts\t\ttotal instructions executed\n"; }
if($fp_fma_ops){ print "$fp_fma_ops\t\ttotal FPU multiply-add operations\n"; }
if($cycles){ print "$cycles\t\ttotal cycles\n"; }
print "-------------------------------------------------\n";

system("rm -f ${OUTPUTDIR}/pid.*");
