Performance testing in PHP I need to test performance of a function in PHP. This has to happen accurately, of course. In the end I need to know how long it takes for a function to perform. What I'm doing now:

&lt;?php
$start = microtime(true);
while (microtime(true) != $start + 1); // Wait a second to start up

$loops = 10;
$avg = 0;
for ($i = 0; $i &lt; $loops; $i++) {
    $start = microtime(true);
    for ($c = 0; $c &lt; 1000; $c++) {    // the 1000 may vary depending on the function
        theFunction();
    }
    $end = microtime(true);

    echo "Take $i: " . ($end-$start) . "s\n";

    $avg *= $i;
    $avg += $end - $start;
    $avg /= $i + 1;
}

echo "Average: " . $avg . "s\n";
?&gt;


Is this a good way to test performance of a function in PHP? It returns about the same result all the time, within a margin of ~5% when the server does nothing else.

Let's assume the environment is clean (i.e. the server doesn't have to do anything else in the meanwhile), would this code be good for testing, or does it count too much or too little?
I don't see any immediate problems with it, but I would probably simplified it a bit. Not sure why you're doing it in two loops like that, but I might be missing something of course :)

&lt;?php
$loops = 10000;

$start = microtime(true);

for ($i = 0; $i &lt; $loops; $i++)
    theFunction();

$total = microtime(true) - $start;
$avg = $total / $loops;

echo "Average: " . $avg . "s\n";