Search code examples
phpmysqlexecution-time

Calculating Time of a query php & Mysql


I am trying to calculate the time it takes a query to run using a php script:

For example:

$sql = "SELECT COUNT(*) FROM `order_items` LEFT JOIN `orders` ON `oi_o_id` = `o_id` WHERE `o_status` = 'completed' AND `oi_p_id` = '10' LIMIT 1";
$sqlStart = getMicroTime();
$result = mysql_query($sql);
$sqlEnd = getMicroTime();
$sqlTime = $sqlEnd - $sqlStart;

echo $sqlTime;

function getMicroTime() {
    list($msec, $sec) = explode(' ', microtime());
    return floor($sec / 1000) + $msec;
}

This appears to work most of the time, but occasionally I get a negative value e.g. -0.98840499995276. How is this possible? and is there a better way to get the query execution time?

Thanks


Solution

  • Your microtime function is not necessary, simply do

    $start = microtime(TRUE);
    ... do query
    $end = microtime(TRUE);
    

    passing in the TRUE value has microtime() return the timestamp as an actual float, not that moronic string format that some [truly nasty but accurate description of said person's intelligence] thought would be a useful way of returning the data.