Finding and fixing bottlenecks-slow parts in your PHP code
Sometimes you can see that your script is running slow but if you don’t have a lot of experience you don’t know how to find out what’s the problem and where to start looking for it.
You then naturally start looking at your loops and things like that, but from my experience the bottleneck is almost always somewhere you are not expecting.
It’s often in your database queries or calling external resources. The ones that look so innocent
To find out where the issue is, you can use these two functions:
function benchmark() { static $start = NULL; if( is_null($start) ) { $start = get_microtime(); } else { $benchmark = get_microtime() - $start; $start = get_microtime(); return $benchmark; } } function get_microtime() { list($usec, $sec) = explode(" ", microtime()); return ((float)$usec + (float)$sec); }
Place these 2 functions on top of your code and place these in your code:
benchmark(); /* The first call will initialize the function */ /* Some code */ echo benchmark() .'<br />'; /* Some more code */ echo benchmark() .'<br />'; /* Yet more code */ echo benchmark() .'<br />';
This will show you numbers like 0.02341… etc.
People usually don’t say how long part of a script should run or how long is too long but I’ll tell you that if you get numbers like 0.1, 0.2, 0.4 or 1.4 then you have a problem and your application might not scale well.
If this is the case then you should use PHPCache and cache the results of those slow parts, even for 1 minute at a time, this will bring those numbers down to 0.02 or 0.01…
The other thing you should do first is to check out your queries, use PHPMyAdmin, try “EXPLAIN your query” and see if MySQL is using your indexes properly. (If you indexed your tables well to begin with)
Query optimization is a big topic, I will write about that more later but sometimes query optimization won’t help you because your query is too nasty and you can’t do it any other way. (With your level of experience)
I hope this helps someone
Permalink for Finding and fixing bottlenecks-slow parts in your PHP code

