25
Jul
0
PHP – Script benchmark / bottleneck debugging snippet
Here’s a really simple function that I use for finding bottlenecks in php scripts. You can add any number of steps to the the script using the microtime() function, and this function shows the execution time of each step.
/** * Benchmark a php script * * @param array $time_sample * @return string HTML */ function quick_benchmark($time_sample = array()) { $steps = count($time_sample); $output = ''; for($i=0;$i<$steps;$i++) { if($i<($steps-1)) { $output .= '<p>Time '. ($i+1) .': '. number_format(($time_sample[$i+1] - $time_sample[$i]),6,'.','') .' seconds.</p>'; } } $output .= '<p>Total time: '. number_format(($time_sample[$steps-1] - $time_sample[0]),6,'.','') .' seconds.</p>'; return $output; } |
This is a simple example using sleep() to demonstrate the output.
$time_sample[] = microtime(true); //start sleep(1); $time_sample[] = microtime(true); //time 1 sleep(2); $time_sample[] = microtime(true); //time 2 sleep(3); $time_sample[] = microtime(true); //time 3 sleep(1); $time_sample[] = microtime(true); //time 4 echo quick_benchmark($time_sample); |
The script outputs:
Time 1: 1.001833 seconds.
Time 2: 2.001427 seconds.
Time 3: 3.001124 seconds.
Time 4: 1.001720 seconds.
Total time: 7.006104 seconds.
It’s a good idea to comment each time you record a microtime so that you know which section of script took that amount of time.
Enjoyed reading this post?
Subscribe to the RSS feed and have all new posts delivered straight to you.
Subscribe to the RSS feed and have all new posts delivered straight to you.