目录

CodeIgniter - 基准测试( Benchmarking)

设定基准点数

如果要测量执行一组行或内存使用所花费的时间,可以使用CodeIgniter中的基准点来计算它。 CodeIgniter中有一个单独的“ Benchmarking ”类用于此目的。

该类自动加载; 你不必加载它。 它可以在控制器,视图和模型类中的任何位置使用。 您所要做的就是标记起点和终点,然后在这两个标记点之间执行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(); 
?>

例子 (Example)

创建一个名为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将启用探查器,它将产生一个输出,如以下屏幕截图所示。

查看示例

要禁用分析,请执行以下URL。

http://yoursite.com/index.php/profiler/disable
↑回到顶部↑
WIKI教程 @2018