David Weng
David Weng

Reputation: 4235

How to measure PHP performance?

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

Upvotes: 11

Views: 4064

Answers (4)

Your Common Sense
Your Common Sense

Reputation: 157863

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><>";
}

Upvotes: 0

Guillermo
Guillermo

Reputation: 947

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";

Upvotes: 1

Sarfraz
Sarfraz

Reputation: 382696

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.

Upvotes: 8

VolkerK
VolkerK

Reputation: 96159

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

Upvotes: 4

Related Questions