PHP & Web Development :: PHP Execution Time Class - 7/10/2007

Bullet The Basics

Ever wanted to benchmark certain code segments, actions, or the exeuction of your entire script in PHP? Knowing the execution time of different parts of your code is very valuable information. You can assess whether further code optimizaion need be done, or whether parts of the script should be on different pages. You can gauge the file access times when you query your database or open a local or remote file inside of a script. Benchmarking code constructs is the basis of my PHP Benchmarking section, where I experiment to find out which constructs of PHP code are faster than others.

Bullet The Script

This script is a simple object-oriented, PHP4+ compatible class. Being object oriented allows multiple TimeCounter objects to exist on one page, or on different pages throughout the site. While you can copy this class into each page that you want to use it on, the best way is to include it in its own file at the top of your page as shown below.

The TimeCounter() class is shown below:

BulletUsage

Using this class is simple. After initializing a TimeCounter object, call the startCounter() function on it. Then execute the code you want to be timed. When you are done, call the stopCounter() function on your TimeCounter object. To output the result, echo the results of calling the getElapsedTime() function on your TimeCounter object.

BulletScript Notes

The time will be returned in milliseconds, which are one thousadth of a second, and will be rounded to 2 decimal points. Because this script is object oriented, you can declare as many TimeCounter() objects as you want and they can all be used concurrently.

BulletExtending this Example

I use this class often in my web applications. Usually, I display the execution time of the entire script in the footer of each page. This allows me to quickly and easily determine any potential bottlenecks as I test the application. And, more importantly, as the application ages, I can come back and test it again and again without having to change any code.