PHP: Get query execution time.

This is a short guide on how to measure the execution time of an SQL query with PHP. This can be extremely useful for debugging purposes (frameworks such as CakePHP have this built into their development mode).

An example of query execution time being measured in PHP:

A step-by-step guide to the code snippet above:

  1. We record the UNIX time in microseconds by using PHP’s microtime function. We record this timestamp BEFORE the SQL query is executed.
  2. We execute our SQL query.
  3. We record the UNIX time again.
  4. We work out how many microseconds have passed by subtracting the $start time from the $end time.
  5. We format the result so that only 10 decimal places are shown (you can change this to whatever you want to).
  6. We print out the formatted result.

You can also use this logic to measure the execution time of other PHP operations, such as function calls and API calls.

Facebook Comments