views:

86

answers:

4

How can I benchmark certain peices of code in PHP? I can use timers to calculate the differences, I'm just not sure if it is the best solution out there.

+3  A: 

You can use a profiler like the one built into Xdebug.

VolkerK
or Zend Debugger if using Zend Studio
Gordon
+5  A: 

Have a look at XDebug Profiler to benchmark the performance and more.

Xdebug's Profiler is a powerful tool that gives you the ability to analyze your PHP code and determine bottlenecks or generally see which parts of your code are slow and could use a speed boost.

Sarfraz
And if you're on Linux, use kcachegrind to visualize the resulting profile files.
therefromhere
A: 

XDebug is cool but if you dont want to install this library, you could try the following:

What I use to locate possible bottle necks is:

$benchmark_start = microtime(true);
// Code goes here
$benchmark_stop = microtime(true);
$benchmark_total = $benchmark_stop - $benchmark_start;
echo "The script took ". $benchmark_total." seconds";
Guillermo
+1  A: 

a bit more sophisticated example of manual profiling using timers
works perfect for me, especially when I am asked to sort things out on some live server with FTP access only.
needless to mention that profiling is way more important (and useful) on live server, rather than on hothouse developer's PC.

$TIMER['start']=microtime(TRUE);
// some code
$query="SELECT ...";
$TIMER['before q']=microtime(TRUE);
  $res=mysql_query($query);
$TIMER['after q']=microtime(TRUE);  
  while ($row = mysql_fetch_array($res)) {
// some code
  }
$TIMER['array filled']=microtime(TRUE);  
// some code
$TIMER['pagination']=microtime(TRUE);  

if ('127.0.0.1' === $_SERVER['REMOTE_ADDR']) { //I set my IP here
  echo "<table border=1><tr><td>name</td><td>so far</td><td>delta</td><td>per cent</td></tr>";
  reset($TIMER);
  $start=$prev=current($TIMER);
  $total=end($TIMER)-$start;
  foreach($TIMER as $name => $value) {
    $sofar=round($value-$start,3);
    $delta=round($value-$prev,3);
    $percent=round($delta/$total*100);
    echo "<tr><td>$name</td><td>$sofar</td><td>$delta</td><td>$percent</td></tr>";
    $prev=$value;
  }
    echo "</table><>";
}
Col. Shrapnel
I'd hardly call this sophisticated.
Raveren
oh yes, you're right! genius would be more appropriate word
Col. Shrapnel