php中怎么使用yield提升性能,针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。
demo1.php
<?php
$startMemory=memory_get_usage();
$startTime=time();
functionconvert($size)
{
$unit=array('b','kb','mb','gb','tb','pb');
return@round($size/pow(1024,($i=floor(log($size,1024)))),2).''.$unit[$i];
}
functionsquares($start,$stop){
$info='';
$square=0;
for($i=$start;$i<$stop;$i++){
$square=$i*$i;
$info.=$i.'squaredis'.$square.PHP_EOL;
}
return$info;
}
$info=squares(0,50000);
echo$info.PHP_EOL;
$endTime=time();
$useTime=$endTime-$startTime;
$endMemory=memory_get_usage();
$useMemory=$endMemory-$startMemory;
echo"总共占用的内存大小为:".convert($useMemory).PHP_EOL;
echo"总共占用的时间为:".$useTime.'秒'.PHP_EOL;
运行结果如下:
49993 squared is 249930004949994 squared is 249940003649995 squared is 249950002549996 squared is 249960001649997 squared is 249970000949998 squared is 249980000449999 squared is 2499900001
总共占用的内存大小为:1.28 mb总共占用的时间为:5秒
demo2.php
<?php
$startMemory=memory_get_usage();
$startTime=time();
functionconvert($size)
{
$unit=array('b','kb','mb','gb','tb','pb');
return@round($size/pow(1024,($i=floor(log($size,1024)))),2).''.$unit[$i];
}
functionsquares($start,$stop){
for($i=$start;$i<$stop;$i++){
yield$i=>$i*$i;
}
}
foreach(squares(0,50000)as$n=>$square){
echo$n.'squaredis'.$square.PHP_EOL;
}
$endTime=time();
$useTime=$endTime-$startTime;
$endMemory=memory_get_usage();
$useMemory=$endMemory-$startMemory;
echo"总共占用的内存大小为:".convert($useMemory).PHP_EOL;
echo"总共占用的时间为:".$useTime.'秒'.PHP_EOL;
运行demo2.php结果如下:
49988 squared is 249880014449989 squared is 249890012149990 squared is 249900010049991 squared is 249910008149992 squared is 249920006449993 squared is 249930004949994 squared is 249940003649995 squared is 249950002549996 squared is 249960001649997 squared is 249970000949998 squared is 249980000449999 squared is 2499900001总共占用的内存大小为:32 b总共占用的时间为:5秒
关于php中怎么使用yield提升性能问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注恰卡编程网行业资讯频道了解更多相关知识。