Getting the actual (absolute) execution time of the last query in PHP (excluding network latency etc)
-
26-09-2019 - |
Question
I want to get the actual Mysql query execution times while they run in my project so running PHP microtime()
before and after and subtracting won't work.
When we run a query in command line, the result displays the timing information something like this:-
xxx rows affected in YY sec
How to get the same time information using PHP. I searched in PHP's Mysql functions in other SO question Here,and here but did not get anything similar. Is there no such PHP function like mysql_error()
, mysql_affected_rows()
which return other important information? If not why is it not there? Any reasoning?
Someone says -
I think that best way to get execution time is to use some program execution functions like exec() or system().
Does anybody have a working PHP code which returns the actual execution time?
Solution
try this:
<?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');
?>
the first if gives you the overall execution time for your query like this:
array(3) { [0]=> string(1) "1" [1]=> string(10) "0.00024300" [2]=> string(17) "SELECT * FROM abc" }
the second if gives you the detaild execution times of your query. the results should be exact since you are using the mysql internal profiler.