CodeIgniter - 基準測試



設定基準點

如果您想測量執行一組程式碼行或記憶體使用所需的時間,您可以使用 CodeIgniter 中的基準點進行計算。CodeIgniter 中為此目的提供了一個單獨的“基準測試”類。

此類會自動載入;您無需載入它。它可以在您的控制器、檢視和模型類中的任何位置使用。您只需標記一個起點和一個終點,然後在這兩個標記點之間執行elapsed_time()函式,您就可以獲得執行該程式碼所需的時間,如下所示。

<?php 
   $this->benchmark->mark('code_start');
  
   // Some code happens here  

   $this->benchmark->mark('code_end');
  
   echo $this->benchmark->elapsed_time('code_start', 'code_end'); 
?>

要顯示記憶體使用情況,請使用函式memory_usage(),如下面的程式碼所示。

<?php 
   echo $this->benchmark->memory_usage(); 
?>

示例

建立一個名為Profiler_controller.php的控制器,並將其儲存在application/controller/Profiler_controller.php

<?php 
   class Profiler_controller extends CI_Controller {
  
      public function index() {
	
         //enable profiler
         $this->output->enable_profiler(TRUE); 
         $this->load->view('test'); 
      } 
  
      public function disable() {
	
         //disable profiler 
         $this->output->enable_profiler(FALSE); 
         $this->load->view('test'); 
      }
		
   } 
?>  

建立一個名為test.php的檢視檔案,並將其儲存在application/views/test.php

<!DOCTYPE html> 
<html lang = "en">
 
   <head> 
      <meta charset = "utf-8"> 
      <title>CodeIgniter View Example</title> 
   </head>
	
   <body> 
      CodeIgniter View Example 
   </body>
	
</html>

更改application/config/routes.php中的routes.php檔案以新增上述控制器的路由,並在檔案末尾新增以下行。

$route['profiler'] = "Profiler_controller"; 
$route['profiler/disable'] = "Profiler_controller/disable"

之後,您可以在瀏覽器位址列中鍵入以下 URL 來執行示例。

http://yoursite.com/index.php/profiler

上述 URL 將啟用效能分析器,並生成如下所示的輸出。

View Example

要停用效能分析,請執行以下 URL。

http://yoursite.com/index.php/profiler/disable
廣告