PHP 計算代碼運行所占內存和時間


PHP 計算代碼運行所占內存和時間

在PHP開發過程中,寫出高質量的代碼是很重要的,除了代碼必須規范之外,性能也是不可忽視的一方面,那么如果檢驗一段代碼是否高效呢,可通過以下一段php代碼來粗略檢測

 1 header("Content-type: text/html; charset=utf-8");  2 $start = microtime(true);  3 // 記錄內存初始使用
 4 define('DD_MEMORY_LIMIT_ON',function_exists('memory_get_usage'));  5 if(DD_MEMORY_LIMIT_ON) $GLOBALS['_startUseMems'] = memory_get_usage();  6 echo "<pre>";  7 error_reporting(E_ALL);  8 // 讓數據說話  9 // ============================================================================================================================================ 10 // 將檢測代碼復制此處11 
12 
13 
14 // ============================================================================================================================================
15 $end = microtime(true); 16 $use_time = number_format($end-$start, 8); 17 echo "\n開發:qfsoft"; 18 echo "\n耗時:".$use_time."秒"; 19 echo "\n內存:"; 20 echo DD_MEMORY_LIMIT_ON ? number_format((memory_get_usage() - $GLOBALS['_startUseMems'])/1024,2).' KB':'不支持'; 21 echo "\n內存峰值:".number_format(memory_get_peak_usage()/1024,2).' KB';

比如,計算1~10000求和

1 // 在1~100000求和
2 $sum = 1; 3 for ($a=1;$a<10000;$a++) { 4     $sum += $a; 5 } 6 echo '和為'.$sum."\n";

結果為:

1 和為49995001 2 
3 開發:qfsoft 4 耗時:0.00200009秒 5 內存:1.00 KB 6 內存峰值:246.55 KB

在此,特別感謝qfsoft先生,給與的代碼支持,希望qfsoft先生身體健康,事業有成,闔家幸福!


免責聲明!

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



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