Created
March 4, 2021 08:36
-
-
Save wcomnisky/349c80094955320555d325475f24f143 to your computer and use it in GitHub Desktop.
PHP Yield (Generator)
This file contains 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 | |
ini_set('memory_limit', '4096M'); | |
$timeStart = microtime(true); | |
$mem = memory_get_usage(true); | |
function arange($start, $end) { | |
$array = array(); | |
for ($i = $start; $i <= $end; $i++) { | |
$array[] = $i; | |
} | |
return $array; | |
} | |
function yrange($start, $end) { | |
for ($i = $start; $i <= $end; $i++) { | |
yield $i; | |
} | |
} | |
$range = arange(1, 10000000); | |
foreach( $range as $num) { | |
if ($num % 2 != 0 || $num % 1000000 != 0) { | |
continue; | |
} | |
echo $num . PHP_EOL; | |
} | |
$memEnd = memory_get_usage(true); | |
$timeStop = microtime(true); | |
var_dump([ | |
'memUsage:' => $memEnd - $mem, | |
'memPeak' => memory_get_peak_usage(true)/(1024**2), | |
'timeSpent' => $timeStop - $timeStart | |
]); | |
// Array | |
// array(3) { | |
// 'memUsage:' => | |
// int(0) | |
// 'memPeak' => | |
// double(514.00390625) | |
// 'timeSpent' => | |
// double(16.428406953812) | |
// } | |
// Yield | |
// array(3) { | |
// 'memUsage:' => | |
// int(0) | |
// 'memPeak' => | |
// int(2) | |
// 'timeSpent' => | |
// double(15.792601108551) | |
// } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment