# Measuring Performance PHP

Three factors affect the time it takes to go from clicking on a link to seeing a completed Web page. First is the network. Your request must travel from the browser to the server, and the Web page must travel back to your browser. This will vary with location and the speed of connection. Second is the time it takes for a browser to display a Web page, once it has the HTML. Neither of these things is a function of PHP itself. Furthermore, they are largely outside of our control. We can try to keep the size of the HTML document small, and we can avoid complex HTML like nested tables, but we can't upgrade everyone's 28.8 modem. What we can control is the time it takes to assemble an HTML document with a PHP script.

The best way to measure how long a script runs is to print the time in important points in your script. Because most scripts take less than a second to run, you must use the microtime function. If you place the output in HTML comments, the display of the page will not be disturbed. Of course, the print statement itself will take some time. You can minimize this by simply printing the output of microtime instead of trying to convert its output into an integer. You can do the math later by hand or in a spreadsheet.

This is a contrived example of a script that performs complex math, then writes to a file. The first HTML comment contains the time on the clock when the script begins. That's followed by time when the 10,000 cosine calculations have finished. Finally we see the time when the 10,000 lines are written to a file.

Output of microtime The microtime function returns two numbers. The first is a fraction of a second, the other the number of seconds since January 1, 1970. Notice that from the first comment to the next, the number of seconds changed from 950996931 to 950996932. The fraction changed from 0.95462500 to 0.38373500. In total 0.42911 seconds elapsed. Doing the math for the second part shows it took 0.080332 seconds. If the performance of this script were not satisfactory, I'd first look into improving the first half. It takes five times longer to execute than the rest.

Measuring Script Performance

<?
print(" <!-- " . microtime() . " --> ");
//fake some long calculation
for($index = 0;$index 10000; $index++) {$value += (cos(time()%360));
}
print(" <!-- " . microtime() . " --> ");
//write to file
$fp = fopen("data.txt", "w"); for($index = 0; $index < 10000;$index++)
{
fputs($fp, "Testing performance "); } fclose($fp);
print(" <!-- " . microtime() . " --> ");
?>

PHP Topics