您好,登錄后才能下訂單哦!
php中怎么使用yield提升性能,針對這個問題,這篇文章詳細介紹了相對應的分析和解答,希望可以幫助更多想解決這個問題的小伙伴找到更簡單易行的方法。
demo1.php
<?php $startMemory = memory_get_usage(); $startTime = time(); function convert($size) { $unit=array('b','kb','mb','gb','tb','pb'); return @round($size/pow(1024,($i=floor(log($size,1024)))),2).' '.$unit[$i]; } function squares($start,$stop){ $info = ''; $square = 0; for($i=$start;$i<$stop;$i++){ $square = $i*$i; $info .= $i.' squared is '.$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 2499300049
49994 squared is 2499400036
49995 squared is 2499500025
49996 squared is 2499600016
49997 squared is 2499700009
49998 squared is 2499800004
49999 squared is 2499900001總共占用的內存大小為:1.28 mb
總共占用的時間為:5秒
demo2.php
<?php $startMemory = memory_get_usage(); $startTime = time(); function convert($size) { $unit=array('b','kb','mb','gb','tb','pb'); return @round($size/pow(1024,($i=floor(log($size,1024)))),2).' '.$unit[$i]; } function squares($start,$stop){ for($i = $start;$i<$stop;$i++){ yield $i=>$i*$i; } } foreach(squares(0,50000) as $n=>$square ){ echo $n.' squared is '.$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 2498800144
49989 squared is 2498900121
49990 squared is 2499000100
49991 squared is 2499100081
49992 squared is 2499200064
49993 squared is 2499300049
49994 squared is 2499400036
49995 squared is 2499500025
49996 squared is 2499600016
49997 squared is 2499700009
49998 squared is 2499800004
49999 squared is 2499900001
總共占用的內存大小為:32 b
總共占用的時間為:5秒
關于php中怎么使用yield提升性能問題的解答就分享到這里了,希望以上內容可以對大家有一定的幫助,如果你還有很多疑惑沒有解開,可以關注億速云行業(yè)資訊頻道了解更多相關知識。
免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內容。