- time: documentation ( source)
<?php
// The slow, although default way of doing fibonacci ---------------------------
function _fibs($n)
{
if ($n < 2)
return $n;
else
return _fibs($n-1) + _fibs($n-2);
}
function fibs()
{
$i = 0;
while (1)
yield _fibs($i++);
}
// The speedy way to do fibonacci-----------------------------------------------
function fibf()
{
$a = 0;
$b = 0;
$t = 1;
while (1)
{
yield $b;
if ($b > 0) {
$t = $a;
$a = $b;
}
$b += $t;
}
}
// Test utils ------------------------------------------------------------------
//
// function to test an iterator by iterating it until the $compare function
// returns false
//
// print the result visually because its sexy
function visual_iterator_tester($fn, $cmpr)
{
echo "timing $fn ";
$then = time();
foreach ($fn() as $f)
{
if ($cmpr($f)) break;
echo ".";
}
$now = time();
$diff = $now - $then;
echo "\n$fn completed in $diff second(s)\n";
}
// Run the damn thing ----------------------------------------------------------
$fns = ['fibs', 'fibf'];
$runs = 9999999;
foreach ($fns as $fn)
visual_iterator_tester($fn, function($a) use($runs) { return $a > $runs; });