PHP performance checking (for example: because of Dreamhost CPU usage warning)
If you want to optimize your PHP script or find out what part of your PHP script causes problems (for example consumes too much CPU time on Dreamhost) - below you can find solution how to do it - how to check - chow long selected parts of your PHP script work.
For our convenience we need to prepare two usefull funcions, first to start timer, second to stop it and log some information into the log file.
//this funcion starts timer
function startLog(){
global $startTime;
$startTime = microtime();
}
//this funcion stops timer and logs some information to log
function stopLog($info){
global $startTime;
$startT = explode(’ ‘, $startTime);
$endT = explode(’ ‘, microtime());
$workTime = ($endT[1]+$endT[0]) - ($startT[1]+$startT[0]);
$f = fopen(’performance.log’, ‘a’, 1);
// time work_time info REQUEST_URI REMOTE_ADDR HTTP_USER_AGENT
fwrite($f, date(’m-d-Y H:m:s’) . “\t”.$workTime . “\t[” . $info . “]\t” . $_SERVER[’REQUEST_URI’] . “\t” . $_SERVER[’REMOTE_ADDR’] . “\t” . $_SERVER[’HTTP_USER_AGENT’] . “\n”);
fclose($f);
}
NOTICE: you must ensure that your www serwer (for example Apache) can write to specified location - where your performance.log file should be placed.
now you should put these functions in PHP file you want to measure, and put functions invocations in apropriate file places
for example - if you want to measure some part of your code
startLog();
…
here is your part of script you want to measure
…
stopLog(”some specific information that block of code”);
Of course you can measure more than one part of your code and you can put your funcions agains in another place
startLog();
…
here is your part of script you want to measure
…
stopLog(”measuring second block of my code”);
Example of log file:
01-26-2006 18:01:11 0.044380903244019 [some specific information that block of code] /wordpress2/ 127.0.0.1 Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.8) Gecko/20051111 Firefox/1.5