2
\$\begingroup\$

All I want do to is simply get the result of how long (in seconds) the PHP takes to process the SQL query. Am I on a right track? Is my code correct to get the result I want?

<?php
$con = mysql_connect("localhost","root","");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db("test3", $con);

    $start = microtime(TRUE);
    $result = mysql_query("SELECT * FROM `test`
    ORDER BY `test`.`test2` DESC
    LIMIT 0,100");


echo "<table border='1'>
<tr>
<th>ID</th>
<th>test1</th>
<th>test2</th>
<th>test3</th>
<th>test4</th>
</tr>";

while($row = mysql_fetch_array($result))
  {
  echo "<tr>";
  echo "<td>" . $row['ID'] . "</td>";
  echo "<td>" . $row['test1'] . "</td>";
  echo "<td>" . $row['test2'] . "</td>";
  echo "<td>" . $row['test3'] . "</td>";
  echo "<td>" . $row['test4'] . "</td>";
  echo "</tr>";
  }
echo "</table>";

$end = microtime(TRUE);

$sqlTime = $end - $start;


mysql_close($con);
echo $sqlTime
?>   
\$\endgroup\$

1 Answer 1

2
\$\begingroup\$
  1. Yes, microtime is designed to be used for this. The PHP documentation mentions this use case for microtime().
  2. Consider putting this into a loop and print out the average result: if the measured time is too small, you can't provide a reliable estimation.
  3. Concerning the MySQL request: you should switch to mysqli or PDO.
\$\endgroup\$
2
  • \$\begingroup\$ Thanks, for the connection advice. I will change that, but I am still concerned whether $end = microtime (TRUE) is the right place to have? Or should I put it after the sql query? \$\endgroup\$
    – fn24
    Commented Mar 13, 2012 at 15:44
  • \$\begingroup\$ It simply depends on what you want to measure: if it's simply MySQL, put it at the end, and if you want to include PHP processing, keep it there. \$\endgroup\$ Commented Mar 13, 2012 at 15:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.