Search form

Search

PHP: Elapsed time and page performance

Submitted by dziemecki on Sat, 10/02/2010 - 11:17

A recent project had me scouring a code base for the cause of a site's incredibly poor performance. The site was pulling data from all over the place, and the code was extremely modular, nested, and non-linear, so tracking down the actual "Herbie" in the process was a real challenge. One of the first things I did was put together some "stopwatch" code to test the length of time each section took to run, as well as to test the impact of various changes on overall page load times. Here's what I came up with to measure and output the information.

The key to the entire exercise is a native PHP function called "microtime". This function returns, in seconds and microseconds, the length of time from the Unix "Epoc" (1/1/70 Midnight) to the current instant. To use it like a stop watch, you simply get a time stamp before the item to be measured, and then compare it to another one afterwards.

On to the nuts and bolts.

To start off, you need to initialize the key variables in the global area of you page, preferably at the very top before any cycle-consuming activities occur:

All that's happening here is that I am taking an earlier time stamp passed to me, either the first one or the most recently made one, and comparing it against a new "current" stamp. The only "tricky" part is exploding the seconds and microseconds out of the microtime return. Do a little math, re-set the value of $sLastTime, and return the difference, in seconds.

To use the function, first make sure the passed time stamp is in scope. If you are in a function or otherwise unable to access global variables, declare the timestamp you need.

global$sLastTime;
orglobal$sStartTime;

If intervening code you are not currently focused on has burned some cycles, you can add this right before the area you want to time in order to re-set the clock:

About

I'm Dan Ziemecki, the author of this site and a technology professional working in the Atlanta area. "Excellent Cruft" is a journal wherein I log the lessons of my various projects (before I forget them) in an effort to give back to the community. Feel free to use anything you find here.