计算一个页面中的数据库查询次数和用时

很多博客软件都有这么一个功能,比如“生成本次页面一共花费了xx毫秒,进行了xx次数据库查询”等等。那么这个功能是如何实现的呢,下面我大概说下思路。

1. 在类的构造函数中声明全局变量

定义一个全局变量 $queries 用来统计页面生成经过的数据库查询次数。

1 function __construct()
2 {
3     parent::__construct();
4     global $queries;
5 }

2. 修改数据库类中封装好的的 query()

你应该有用到数据库类吧,找到它封装 query() 的方法,比如下面的:

1 // 执行SQL语句
2 public function query($query)
3 {
4     //echo $query.'<br />';
5     ++$GLOBALS['queries'];
6     return $this->result = mysql_query($query, $this->link);
7 }

那么每执行一次 Query,全局变量 queries 就会自增1。

3. 在方法体中这样写:

1 public function content($id = 0)
2 {
3     $GLOBALS['queries'] = 0;
4     // something to do
5     echo $GLOBALS['queries'];
6 }

就这么简单就能实现那个功能了。

4. 附带计算PHP脚本执行的函数

之前写的博文介绍了下计算PHP脚本执行时间的函数,这里再贴一下吧。

 1 // 计时函数 
 2 public function runtime($mode = 0) { 
 3     static $t; 
 4     if(!$mode) { 
 5         $t = microtime(); 
 6         return; 
 7     } 
 8     $t1 = microtime(); 
 9     //list($m0,$s0) = split(" ",$t);
10     list($m0,$s0) = explode(" ",$t);
11     //list($m1,$s1) = split(" ",$t1);
12     list($m1,$s1) = explode(" ",$t1);
13     return sprintf("%.3f ms",($s1+$m1-$s0-$m0)*1000); 
14 } 

使用如下:

 

1 public function content($id = 0)
2 {
3     $this -> runtime();
4     $GLOBALS['queries'] = 0;
5     // something to do
6     echo $GLOBALS['queries'];
7     echo $this -> runtime(1);
8 }

 

posted @ 2014-09-17 15:49  hl0128  阅读(377)  评论(0编辑  收藏  举报