获取PHP中最后一个查询的实际(绝对)执行时间(不包括网络延迟等)

问题描述 投票:5回答:1

我想获得它们在我的项目中运行时的实际Mysql查询执行时间,因此在运行PHP microtime()之前和之后以及减去之前都无法运行。

当我们在命令行中运行查询时,结果将显示计时信息,如下所示:-

xxx rows affected in YY sec

如何使用PHP获得相同的时间信息。我在其他SO问题PHP's Mysql functionsHere中搜索了here,但没有得到任何类似的结果。是否没有像mysql_error()mysql_affected_rows()这样的PHP函数返回其他重要信息?如果不是,为什么不在那里?有什么理由吗?

有人说-

我认为获得执行力的最佳方法时间是使用一些程序执行exec()或system()之类的函数。

有人拥有可以返回实际执行时间的有效PHP代码吗?

php mysql function execution-time
1个回答
11
投票

尝试一下:

<?php

$host='localhost';
$username='testing';
$password='testing';
$dbname='test';

$DBC = new mysqli($host,$username,$password,$dbname);

$DBC->query('set profiling=1');
$DBC->query('SELECT * FROM abc');
if ($result = $DBC->query("SHOW profiles", MYSQLI_USE_RESULT)) {


    while ($row = $result->fetch_row()) {
        var_dump($row);
    }
    $result->close();
}
if ($result = $DBC->query("show profile for query 1", MYSQLI_USE_RESULT)) {


    while ($row = $result->fetch_row()) {
        var_dump($row);
    }
    $result->close();
}
$DBC->query('set profiling=0');

?>

第一个if语句为您提供了查询的总体执行时间,如下所示:

array(3) { [0]=>  string(1) "1" [1]=>  string(10) "0.00024300" [2]=>  string(17) "SELECT * FROM abc" }

第二个if语句为您提供了查询的详细执行时间。结果应该准确,因为您正在使用mysql内部分析器。

© www.soinside.com 2019 - 2024. All rights reserved.