Last active
December 21, 2015 07:09
-
-
Save ChrisBuchholz/6269324 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?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; }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment