Profiling with time() and microtime()

 

PROFILING WITH TIME() AND MICROTIME()

 

 

Code profiling is the analysis of various metrics related to code performance and efficiency.

If a PHP script is taking too much time to complete, it’s a good idea to profile the script to find out the cause.

 

The first thing to do is to isolate the piece of code (or the different pieces of code) responsible for the long execution time.

It could be an unoptimized function working on a large set of data, a slow SQL query, or a wrong iteration going out of control.

 

A very easy and straightforward way to perform this analysis is to use the time() and microtime() functions.

Both these functions return the current Unix Timestamp. time() returns it in seconds, while microtime() returns microseconds too.

 

To check the execution time of a piece of code you need to:

  1. Save the current time with time() or with microtime() before the code you want to profile.
  2. After the code, call time() or microtime() again and calculate the difference from the previously saved value.
  3. That is the execution time. 😉

If the execution time is more than a few seconds you can use time(), otherwise it’s usually more useful to use microseconds.

 

This is a practical example:

<?php

$start = microtime(TRUE);

/* Start of the code to profile */
for ($a = 0; $a < 10000000; $a++)
{
	$b = $a*$a;
}
/* End of the code to profile */

$end = microtime(TRUE);
echo "The code took " . ($end - $start) . " microseconds to complete.";

 

 

 

If you have any questions, feel free to ask in the comments below or on my Facebook Group: Alex PHP café.

If this tip has been helpful to you, please spend a second of your time and share it using the buttons below… thanks!

 

Alex