Microsoft Word - Core PHP Programming Using PHP to Build Dynamic Web Sites

(singke) #1

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.


Listing 22.1 is a contrived example of a script that performs complex math, then writes
to a file. Figure 22-1 shows the output. 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.


Figure 22.1. 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.


Listing 22.1 Measuring Script Performance


<?
print("\n\n");


//fake some long calculation
for($index = 0; $index 10000; $index++)
{

Free download pdf