Count number of MySQL queries executed on page

流过昼夜 提交于 2019-11-25 15:19:19

SMF does its query counting by having its own custom query function:

function db_query($db_string, $file, $line)
{
    global $db_cache, $db_count, $db_connection, $db_show_debug, $modSettings;

    // One more query....
    $db_count = !isset($db_count) ? 1 : $db_count + 1;

    ...

The simplest way to achieve what you're trying to do would be to do the same; make a wrapper for mysql_query and use that instead of mysql_query.

SHOW SESSION STATUS LIKE 'Questions'
Andris

I think the following command is a per session count:

SHOW STATUS LIKE 'com_select%'

You can get the number of queries ever executed by calling.

show session status like "Queries";

Call this at the beginning and at the end of page creation, and then you can see how many queries there have been. Don't forget that this command itself is also counted as one.

Here's an example which might be easier to follow than the SMF one.

class QueryLogger
{
    public $queries = array();

    public function query($sql)
    {
        $start = microtime(true);

        $query = mysql_query($sql);

        $queries[] = microtime(true) - $start;

        return $query;
    }

    public function getCount()
    {
        return sizeof($this->queries);
    }

    public function getTime()
    {
        return array_sum($this->queries);
    }
}

$queryLogger = new QueryLogger;
$query1 = $queryLogger->query('...');
$query2 = $queryLogger->query('...');
echo 'Ran '.$queryLogger->getCount().' queries in '.$queryLogger->getTime().' seconds.';

After Quassnoi comment i put this in the start of script:

$res = mysql_query("SHOW SESSION STATUS LIKE 'Questions'");
$row = mysql_fetch_array($res, MYSQL_ASSOC);
define("START_QUERIES",$row['Value']);

and this:

$res = mysql_query("SHOW SESSION STATUS LIKE 'Questions'");
$row = mysql_fetch_array($res, MYSQL_ASSOC);
define("STOP_QUERIES",$row['Value']);

you can see total num of queries with:

echo "No of queries: ".(STOP_QUERIES-START_QUERIES-1);

I don't know why use -1, maybe it counts mysql_select_db statement (or smth) also, but it works pretty good on my localhost

To count the number of queries, you need to count the number of queries. Sorry to sound redundant, but it really is that simple.

Make a counting function (mysql_query_counted?), then use grep to search through your codebase for mysql_query(, and it shouldn't take more than an hour or two. Possibly even think about using sed or similar to replace the function calls.

A note on SMF and similar that have this built-in. They use DB abstraction layers, so they are already using their own query function, and adding query counting at a later date would have been as simple as adding a line incrementing a counter to to that function. +1 for abstraction and encapsulation I suppose.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!