PHP Code Profiling with Execution Time Analysis

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

If it takes a long time to complete a PHP script, it is a good idea to profile the script to find out why.

The first thing to do is to isolate the pieces of code that might be responsible for the long execution time.

It can be caused by an unoptimized function that runs on a large dataset or it can be a slow SQL query or perhaps an incorrect iteration out of control.

After an analysis of the execution time of these pieces of code, it is quite simple to identify the problem.

Script execution time in PHP is basically the time required to execute the PHP script. Use the clock time instead of the CPU execution time to calculate script execution time. Knowing the clock time before and after script execution will help you know the script execution time.

You can get the clock time using the microtime() function. Use it before starting the script, and then at the end of the script. Then use the formula (End time – Start time). The microtime() function returns time in seconds. Execution time is not fixed, it depends on the processor.

$start_time = microtime(); // Start counting

// Your code

printf('It took %.5f sec', microtime() - $start_time);

This snippet of code can visualise the execution time for you.