05.05.2013 Views

Programming PHP

Programming PHP

Programming PHP

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

changes you make to your code as you attempt to improve its speed—we show you<br />

how to time individual portions of a page in the next section, but ultimately these<br />

microbenchmarks don’t matter if the overall page is still slow to load and run. The<br />

ultimate proof that your performance optimizations have been successful comes<br />

from the numbers that ab reports.<br />

Profiling<br />

<strong>PHP</strong> does not have a built-in profiler, but there are some techniques you can use to<br />

investigate code that you think has performance issues. One technique is to call the<br />

microtime( ) function to get an accurate representation of the amount of time that<br />

elapses. You can surround the code you’re profiling with calls to microtime( ) and<br />

use the values returned by microtime( ) to calculate how long the code took.<br />

For instance, here’s some code you can use to find out just how long it takes to produce<br />

the phpinfo( ) output:<br />

<br />

Reload this page several times, and you’ll see the number fluctuate slightly. Reload it<br />

often enough, and you’ll see it fluctuate quite a lot. The danger of timing a single run<br />

of a piece of code is that you may not get a representative machine load—the server<br />

might be paging as a user starts emacs, or it may have removed the source file from<br />

its cache. The best way to get an accurate representation of the time it takes to do<br />

something is to time repeated runs and look at the average of those times.<br />

The Benchmark class available in PEAR makes it easy to repeatedly time sections of<br />

your script. Here is a simple example that shows how you can use it:<br />

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!