PHP獲取代碼段執行的毫秒時間和消耗內存


我們在項目開發經常需要做一些優化型測試,比如優化代碼段,排查代碼段效率問題,或者降低內存消耗成本。

<?php $start_memory = memory_get_usage();                 //開始內存
echo '開始內存:' . $start_memory . '<br>'; $start_time = microtime(true);                         //獲取程序開始執行的時間 //----------------------程序代碼段開始-----------------------------------// $arr = [ 'name' => '風的季節', 'age'  => '29', 'sex'  => 1, 'address' => '山東省德州市慶雲縣', 'qq'   => '645631686', 'phone'=> '15712953567', ]; $all = []; for($i = 0; $i< 1000; $i++) { $str = json_encode($arr); $arr = json_decode($str, true); $all[] = $arr; } unset($all); //----------------------程序代碼段結束-----------------------------------//  $end_time = microtime(true);                        //獲取程序執行結束的時間
$run_time = ($end_time - $start_time) * 1000;       //計算差值 毫秒
echo "[頁面執行時間:{$run_time}]毫秒<br>"; $end_memory = memory_get_usage(); echo '運行后內存:'. $end_memory . '<br>'; echo '使用的內存:' . ($end_memory - $start_memory) . '<br>'; echo '回到正常內存:'.memory_get_usage(); 
//結果
開始內存:390224 [頁面執行時間:2.8541088104248]毫秒 運行后內存:391256 使用的內存:1032 回到正常內存:391256

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM