<?php
function xrange($start, $end, $step = 1) {
while ($start <= $end) {
yield $start;
$start += $step;
}
}
function reduce(Generator $iterator, Callable $callback, $initial = null) {
$result = $initial;
foreach($iterator as $value) {
$result = $callback($result, $value);
}
return $result;
}
$start = microtime(true);
reduce(xrange(1, 140000), function($r, $v) {return $r + $v;}, 0);
$byGen = microtime(true) - $start;
$start =microtime(true);
array_reduce(range(1,140000), function($r, $v) {return $r + $v;}, 0);
$byNormal = microtime(true) - $start;
$percent = ($byGen - $byNormal)*100/$byNormal;
printf("Generator is %s than normal function %.2f%%.\n", ($byGen > $byNormal ? 'Slower' : 'Faster'), abs($percent));
preferences:
24.95 ms | 408 KiB | 5 Q