Saturday, November 20, 2010

MySQL get Query took seconds time taken

Took a bit of time to find this online so here's what I found that works.
This is suppesdly from phpmyadmin (which is where I should've looked) but I was lazy to check there so found it online and worked great!

This is before the query:
list($usec, $sec) = explode(' ',microtime());
$querytime_before = ((float)$usec + (float)$sec);

**query and execution here**

After the query:
list($usec, $sec) = explode(' ',microtime());
$querytime_after = ((float)$usec + (float)$sec);
$querytime = $querytime_after - $querytime_before;

I use functions so this is how I sent back the value:
return array("something" => $something, "qtime" => $querytime);

the function is called normally for outputing the results as well as the time
$thefunction = thefunction(whaterver);

inside the other loop I used this to collect the total queries time together:
$qtime = $thefunction['qtime']+$qtime;

After that, you can output it at the bottom of the page (or where ever):
<?php $strQueryTime = 'Query took %01.4f sec';  echo sprintf($strQueryTime, $qtime); ?>

The final output result will be :
Query took 0.00xxx sec

Let me know what you think in the comments

No comments: