zoukankan      html  css  js  c++  java
  • PHP获取生成一个页面的数据库查询次数(转)

    很多博客软件都有这么一个功能,比如“生成本次页面一共花费了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脚本执行时间的函数,这里再贴一下吧。

    01 // 计时函数
    02 public function runtime($mode = 0) {
    03     static $t;
    04     if(!$mode) {
    05         $t = microtime();
    06         return;
    07     }
    08     $t1 = microtime();
    09     //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 }
  • 相关阅读:
    【读书笔记】《思考,快与慢》
    【2020-12-09】别人看不上的,正是绝佳机会
    员工的重要性
    二叉树的堂兄弟节点
    占位
    数组中重复的数字
    从上到下打印二叉树
    Python生成exe
    二叉搜索树节点最小距离
    第N个斐波那契数
  • 原文地址:https://www.cnblogs.com/qiandu/p/4122547.html
Copyright © 2011-2022 走看看