A common subject on this site is "How much faster is function x versus function y?"
The proper question should be, which parts of my code are gobbling up CPU time, and how can I optimize them as much as possible?
For instance, many beginners ask the question of whether echo is faster than print, or explode is faster than split.
They're pretty much the same, and while there are minor but measurable performance deltas, they aren't big enough to count next to a database connection or a large array being run through an implode function...
What we really should be looking for is the slow parts of our pages. The way to find them is to profile our code. We aren't looking for perfect scientific exactness either, just the slowest parts.
It's really pretty easy. We store microtime() time stamps as we go along, and when we're done, we print out the differences between them. If we're smart about it, it's easy to do with a funtion. Here's how I do it, and yes, it's kind of hackish, but it works.
time[] = microtime();
Is a line you can sprinkle through your code in areas to get a feel for where the work is being done. We won't process the stamp, just hold it til the file finishes running, then spit out the profile info. You can use a simple get url switch to turn it on if you wanna, or just uncomment it when needed.
First, a function to turn microtime into a number we can use for mathmatical calculations. Since microtime returns two numbers seperated by a space, we just need to add them up and return them. The first part is the microsecond counter, then second the seconds portion.
function mtcat(&$microtime){
$tmp = split(" ",$microtime);
$microtime = $tmp[0]+$tmp[1];
}
?>
will do it. Sure, there are cooler ways, but this one is pretty obvious in nature.
So, we have a bunch of time stamps stored in the $time array, what to do with them?
Here's a simple way:
Since we're measuring DELTAs, we don't need
#to process the last entry, just use it to
#comare to the next to last...
#But first we have to change all the stamps
#to numbers we can do math on.
array_walk($time,mtcat);
Next we compare each element with the one
after it. Since there is no element after
the last one, we skip it in the for next
loop
$count = count($time)-1;
$count--;for ($i=0;$i<$count;$i++){
print "Time from checkpoint ";
print $i." to ";
print $i+1 ." was ";
print (float)$time[$i+1] - (float)$time[$i];
print "<BR>\n";
}
Now you'll have some idea how fast each chunk of code runs, and know where to look for problems.