PHP gets the number of database queries that generate a page

Source: Internet
Author: User
Tags php script

Many blog software has such a function, such as "generated this page altogether spent xx milliseconds, XX times database Query" and so on. So how is this function implemented, and below I probably say the idea.

1. Declaring a global variable in the constructor of a class

Defines a global variable $queries used to count the number of database queries generated by the page.

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

2. Modify the query () encapsulated in the database class

You should use the database class to find the method that encapsulates the query (), such as the following:

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

Then each time Query is executed, the global variable queries will increment by 1.

3. Write this in the method body:

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

That's the way it can be done.

4. A function to calculate PHP script execution

The previous blog post describes the calculation of the PHP script execution time function, here to paste a bit.

01 // 计时函数
02 publicfunction 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);
[    ;    list ( $m 1 $s 1 ) =  explode ( $t 1
13     returnsprintf("%.3f ms",($s1+$m1-$s0-$m0)*1000);
14 }

Use the following:

1 publicfunction 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 }

PHP gets the number of database queries that generate a page (RPM)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.