note 93828 deleted from function.microtime by googleguy
| From: | googleguy@php.net | Date: | Tue, 22 Oct 2013 11:17:15 +0000 |
| Subject: | note 93828 deleted from function.microtime by googleguy | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-197075@lists.php.net to get a copy of this message | ||
Note Submitter: strata_ranger at hotmail dot com
----
Another version of a stopwatch-style function, this one with the following features:
- Can evaluate any function (callback) with any arbitrary arguments
- Can specify the # of iterations to run
The obvious caveat is of course to take the return value with a grain of salt, especially since this
one doesn't run in the tightest loop possible. A little eval() work could probably fix that,
but in the meantime calling this function with no arguments will make it establish a reference point
(using pi() ) to measure subsequent calls against -- sort of like hitting the "zero"
button on a food scale.
<?php
function stopwatch()
// stopwatch([$limit], [$callback], [$args ... ])
// $limit - # of iterations to run
// $callback - function to time
// $args - arguments for function
//
{
static $zero = 0;
static $limit = 99999;
$args = func_get_args() + Array(null);
// Check for # iterations, assign for future calls
if (is_integer($args[0])) $max = min(array_shift($args), 999999); else $max = $limit;
if ($max != $limit)
{
$limit = $max;
$zero = 0;
}
if (isset($args[0])) $callback = array_shift($args); else $callback = null;
if (is_null($callback))
{
// Use a very small function as a reference point
$callback = 'pi';
$zero = null;
}
// Ensure a valid callback
if (!is_callable($callback, false, $name)) return null;
if ($name == __FUNCTION__) return null;
// The actual loop
$st = explode(' ',microtime());
for($cx=0; $cx<$max; $cx++)
{
call_user_func_array($callback, $args);
}
// Final calculations
$t = explode(' ', microtime());
$t[0] -= $st[0];
$t[1] -= $st[1];
if (is_array($zero)) // Use previous reference point
{
$t[0] -= $zero[0];
$t[1] -= $zero[1];
}
elseif (is_null($zero)) // or establish a new one
{
$zero = $t;
return;
}
if ($t[0] < 0) // Ensure microseconds are always positive
{
$t[0]++; $t[1]--;
}
// Done
return "$t[1] + $t[0]s";
}
function faster()
{
return;
}
function slower()
{
return fmod(5,2);
}
echo "<p>Comparing two functions...</p>";
var_dump(stopwatch('faster'));
var_dump(stopwatch('slower'));
echo "<p>Comparing 100,000 iterations of two functions...";
var_dump(stopwatch(100000, 'faster'));
var_dump(stopwatch('slower'));
echo "<p>Run a single function 500 times...</p>";
var_dump(stopwatch(500));
var_dump(stopwatch('max', 1, 2, 3, 4, 5));
echo "<p>Run a single function 555,555 times...</p>";
var_dump(stopwatch(555555));
var_dump(stopwatch('max', 1, 2, 3, 4, 5));
echo "<p>Fail sanity test...</p>";
var_dump(stopwatch('stopwatch')); // Attempt to time itself!
?>