Wednesday, March 23, 2011

Get query execution time in PHP

Hi,

When you perform a Google search, it shows the approximate number of records and the time taken to make that search. e.g.


For a layman, that time may seem to be the time taken for the entire process. But actually its the time taken to generate the search results. So technically, its the time taken to execute the search query. I have used the following technique to do the same. But I am sure that can be many more ways to achieve it.

For this I created a simple table just for demonstration as follows:


Now my objective is to run a query on this table and fetch the time required to run that query using PHP. So this is the code that I have written:


<?php
mysql_connect("localhost","root");
mysql_select_db("test");

$start_time=microtime(true);
$resultsets=mysql_query("select * from search_table");
$stop_time=microtime(true);

echo "Total Records: ".mysql_num_rows($resultsets);
echo "<br/>Time taken: ".number_format($stop_time-$start_time,4);

?>

The code is pretty much self explanatory. Before running the query I am storing the current timestamp in a variale "$start_time" and after executing the query, again storing the timestamp in "$stop_time". Now I just simply do a subtraction to get the duration of the query.

That's it. number_format() is used to show just 4 digits after decimal point. Make sure you keep the argument for microtime() as false, else it will return a string with a space in between and the subtraction wont work. The reason I have used microtime() instead of time(), because time() does not return microseconds like microtime().

Finally the output is as follows:

Post in your comments for a better solution.

Cheers!

1 comment: