#!/usr/bin/env php
<?php

# get command line options
require_once ("Console/Getopt.php");
set_include_path ("test/framework/external/" . PATH_SEPARATOR . get_include_path () );
$cg = new Console_Getopt();
$command_line = join (" ", $cg->readPHPArgv());
$opt_result = $cg->getopt($cg->readPHPArgv(), "lhpf");
if (!is_array ($opt_result))
	die ($opt_result->message."\n");

list ($opts, $arguments) = $opt_result;
$opt_help = false;
$opt_long = false;
$opt_php = false;
$opt_fdo = false;
foreach ($opts as $opt) 
{
	switch ($opt[0])
	{
		case 'h': $opt_help = true; break;
		case 'l': $opt_long = true; break;
		case 'p': $opt_php = true; break;
		case 'f': $opt_fdo = true; break;
	}
}

# help message
if ($opt_help || count ($arguments) > 0)
{
	die (<<<EOL
bench - Compiles (with optimization) the Zend benchmark, producing averaged results for 10 runs - phpcompiler.org

Usage: benchmark [OPTIONS]

Options:
	 -h     Print this help message
	 -l     Run the long benchmark, instead of the standard one.
	 -p     Run the benchmark using PHP, instead of compiling the code with phc
	 -f     Use gcc's feedback directed optimizations

EOL
	);
}


$filename = "test/subjects/benchmarks/zend/bench.php";
$command = "./bench.out";

# use long benchmark for -l
if ($opt_long)
{
	$filename = "test/subjects/benchmarks/zend/long_bench.php";
	$command = "./long_bench.out";
}

# which programs to use for testing
if ($opt_php)
	$command = "/usr/local/php-opt/bin/php $filename";
else
{
	print "Initializing test\n";
	if ($opt_fdo)
	{
		print "Generating FDO\n";
		`misc/comp -O -F $filename`;

		print "Using and generating FDO\n";
		`misc/comp -O -f -F $filename`;

		print "Using FDO\n";
		`misc/comp -O -f $filename`;
	}
	else
	{
		`misc/comp -O $filename`;
	}
}


# run the benchmark
for ($i = 0; $i < 10; $i++)
{
	print "Starting benchmark $i: ";
	$results = `$command`;
	process_results ($results);
	echo "\n";
}

dump_results ();



function process_results ($string_input)
{
	global $tally;
	$strings = explode ("\n", $string_input);

	foreach ($strings as $line)
	{
		if (preg_match ("/^(\S+)\s+([\d\.]+)$/", $line, $matches))
		{
#			print "Matching {$matches[1]} with {$matches[2]}\n";
			$tally[$matches[1]][] = $matches[2];
			if ($matches[1] === "Total")
				echo $matches[2];
		}
		else
		{
			if (!($line == "" || preg_match ("/^-*$/", $line)))
				print "Skipping result line: $line\n";
		}

	}
}

function dump_results ()
{
	global $tally;
	foreach ($tally as $key => $result)
	{
		$num = count ($result);
		$average = array_sum ($result) / $num;
		printf ("%-20s ($num):  $average\n", $key);
	}
}

?>
