yield對效能提公升的一次小小測試

2022-03-12 02:40:33 字數 2320 閱讀 8512

生成器提供了一種更容易的方法來實現簡單的物件迭代,相比較定義類實現 iterator 介面的方式,效能開銷和複雜性大大降低。生成器允許你在 foreach **塊中寫**來迭代一組資料而不需要在記憶體中建立乙個陣列, 那會使你的記憶體達到上限,或者會佔據可觀的處理時間。相反,你可以寫乙個生成器函式,就像乙個普通的自定義函式一樣, 和普通函式只返回一次不同的是, 生成器可以根據需要 yield 多次,以便生成需要迭代的值。

有兩個php檔案,demo1.php與demo2.php,兩種不同的方式實現求0,到5000之間的數字的平方值並輸出,並列印指令碼執行的時間與使用的記憶體大小。

demo1.php

<?php

$startmemory = memory_get_usage();

$starttime = time();

function convert($size)

function squares($start,$stop)

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)

function squares($start,$stop)

}foreach(squares(0,50000) as $n=>$square )

$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秒

總結:對比發現,可能由於指令碼計算比較簡單,執行的時間沒啥太大變化。明顯發現使用yield後占用記憶體的量要少很多。說明使用yield還是對效能提公升很有幫助的,像類似的一次性拉取大資料量的資料都可以考慮使用yield實現(資料統計等).

python 乙個小小的效能提公升

你可以通過將函式或方法的定位結果精確地儲存至乙個本地變數來獲得一些效能提公升。乙個迴圈如 for key in token dict key dict.get key,0 1 每次迴圈都要定位dict.get。如果這個方法一直不變,可這樣實現以獲取小小的效能提公升 dict get dict.get...

記一次SQLtuning 效能大幅提公升千倍以上

好久不寫東西了,一直忙於各種雜事兒,恰巧昨天有個使用者研發問到我乙個sql調優的問題,說效能太差,希望我能給調優下,最近有些懶,可能和最近太忙有關係,本來打算問問現在的情況,如果差不多就不調了,那哥們兒說 現在要半個小時才出結果。這個確實有點離譜,這麼慢的效能,再有耐心的人也等不及,沒辦法,只能開工...

第一次小小滴研究彙編

因為想嘗試使用intel cpu的rdtsc指令來為程式計數,所以查閱了相關資料,嘗試後發現gcc下使用rdtsc指令不能獲得正確的結果,於是想看看c的 編譯成彙編的樣子 gcc下得這樣 g o main.s main.cpp s 微軟的cl編譯器得這樣 cl.exe fas main.cpp gc...