Benchmarking is the process of evaluating existing processes and identifying best practices. For example, there are three ways to loop through an array, we would test each method and identify the best performing method. In terms of code, this very often means identifying methods that would be least expensive in terms of CPU time and memory consumption.
Following is a simple benchmark script. It compares while loop with for loop.
$s = microtime(true);
$i=0;
while ($i < 1000000) {
$sm += $i;
$i++;
}
$e = microtime(true);
$t = $e - $s;
print "while loop: $t seconds\n";
$s = microtime(true);
for ($i = 0; $i < 1000000; $i++) {
$sm += $i;
}
$e = microtime(true);
$t = $e - $s;
print "for loop: $t seconds\n";
If you run this code several times, you would see that there is not much difference between the two. This is not surprising as for loop is simply a different syntax of the while loop.
There are usually several ways to code the same task in most languages. Following ia a brief benchmarking summary.
Looping through hash value
// reading values
1. while(list(,$v) = each($h)) {} 100%
2. foreach($h as $v) {} 200%
// reading key,value pairs
1. foreach($h as $k=>$v) {} 100%
2. while(list($k,$v)=each($h)){} 115%
// modifying values
1. while(list(,$v) = each($h)) { $h[$k] = "x"; } 100%
2. foreach($h as $k=>$v) { $h[$k] = "x"} 200%
Note the the 100% in different sections do not correlate. The foreach method would take twice the time the while loop method would take.
To delete many elements from an array, don't use array_splice(). Instead clone array elements you wish to keep.
$newarray[] = clone sarray[elements-to-keep] $array = $newarray;
If you are interested in viewing memory usage, use memory_get_usage() function:
// your code
echo convert(memory_get_usage(true)); // 123 kb
// your code
function convert($size) {
$unit=array('b','kb','mb','gb','tb','pb');
return @round($size/pow(1024,($i=floor(log($size,1024)))),2).' '.$unit[$i];
}
This code was submitted by xelozz at php.net.
Using PEAR Benchmark for benchmarking
To use PEAR benchmark, you need to first install PEAR on your system. Then run the following command to install PEAR benchmark:
pear install benchmark
Once PEAR benchmark in installed, run the following code:
include_once("Benchmark/Timer.php");
$b = new Benchmark_Timer;
$b->start();
$b->setMarker('marker');
// your code goes here
for ($=0; $i <1000000; $i++) {
// 1 million do nothings
}
$b->stop();
// benchmarking information
print_r($b->getProfiling());