This function benchmarks another one specified as first parameter using a callback. The example demostrates how to use callbacks, create lambda-style function and profile your code execution time.
You can use this function as an entry-point to write your own specific function/class for profiling your code.
benchmark.function.php
<?php
/**
* @fn benchmark($function, $parameters = null, $executions = 1)
* @brief Gets the time taken for execute X function Y times
* @param callback $function Function to be called
* @param mixed $parameters Parameters passed to that function
* @param int $executions Number of times the function must be called
* @return PHP5: float Difference between first and last call
* @return PHP4: int Difference between first and last call
*/
function benchmark($function, $parameters = null, $executions = 1)
{
$start_time = null; /* Function call started at */
$end_time = null; /* Function call ended at */
$total_time = 0; /* Total time consumed by benchmark */
$c_executions = 0; /* # of times function was executed */
$mt_call = null; /* Internal microtime() callback func */
$mt_body = null; /* Internal microtime() callback body */
$cb_call = null; /* Internal callback used with $function */
/* The function will be inexistant so check for it */
if (false == function_exists($function))
trigger_error("Function \"$function\" does not exists.", E_USER_ERROR);
/*
* Checks that $executions is a positive integer. If not, fix it
* to 1.
*/
if (!is_int($executions) || $executions <= 0)
$executions = 1;
/*
* This check determines if the $parameters param is an array. In
* that case we must call call_user_func_array, otherwise the call
* is passed to call_user_func
*/
$cb_call = is_array($parameters) ? "call_user_func_array" : "call_user_func";
/*
* Since PHP >= 5.0.0 we can pass "true" as microtime() parameter
* to get the microtime as a float value.
*/
$mt_body = 'return version_compare("5", PHP_VERSION, "<") >= 0
? microtime(true) : microtime();';
$mt_call = create_function(null, $mt_body);
/* Gets the time when the first function call was made */
$start_time = call_user_func($mt_call);