Login

Benchmarking Applications with PHP

Benchmarking a particular application across its different development cycles is one of the most exciting things for a PHP developer. If you’re anything like me, you have had your head spinning with questions, such as… is the performance of my last project good enough? How long does it take to fetch a particular data set from my database? Do I have to implement a caching system? As you can see, these and other dilemmas (add your own to the list) sometimes make peace of mind a nearly impossible goal.

While these problems may eventually affect your mental health, the truth is that they can easily be solved by coding a few simple scripts, or by defining some straightforward functions in PHP to benchmark particular blocks of code, or even an entire application.

Naturally, when it comes to benchmarking the performance of diverse applications, the first method that comes to my mind is the implementation of the popular “microtime()” built-in PHP function. This has become one of the most popular methods for measuring the time consumed by PHP (and other third-party software packages) when performing specific tasks.

Of course, this handy function is used mostly in conjunction with others that are aimed at developing fairly accurate benchmarking applications. You’ve probably utilized it hundreds of times during the development of different web projects. Nevertheless, benchmarking PHP programs is a huge topic that can’t be covered in just a few articles. At least in this new series, I’m going to introduce some basic methods to make the whole process as painless as possible.

By the end of this series, you should be equipped with a decent background on how to benchmark applications with PHP, which is something that can be really useful if you’re careful about developing high-performance programs.

Having outlined the subject of this series, let’s introduce ourselves to the exciting world of benchmarking with PHP. Let’s get going!

{mospagebreak title=Using the microtime() built-in PHP function}

As I expressed in the introduction, one of the simplest ways to create a basic benchmarking mechanism relies on using the “microtime()” built-in PHP function. Just in case you didn’t know, this function returns the current Unix timestamp, which additionally appends the corresponding microseconds to the output.

According to the definition from the PHP manual, the mentioned function returns the string “msec sec,” where sec is the current time measured in the number of seconds since the Unix Epoch (0:00:00 January 1, 1970 GMT), and “msec” is the microseconds part. Both portions of the string are returned in units of “seconds.” In simple terms, the syntax for the “microtime()” function is as follows:

mixed microtime ( [bool get_as_float] )

Additionally, when you’re using PHP 5, the function accepts the optional “get_as_float” parameter, which simply returns the complete timestamp as a float number.

As you may have guessed from the above definition, this function is quite handy for developing a simple benchmarking mechanism that only requires a few lines of code. Therefore, here is a basic custom function that uses “microtime().” Take a look at the definition of this function:

// define ‘getMicrotime()’function in PHP 4

function getMicrotime(){

list($useg,$seg)=explode(‘ ‘,microtime());

return ((float)$useg+(float)$seg);

}

The “getMicrotime()” function that I defined above demonstrates a classic use of “microtime()” to construct a basic benchmarking system. It’s one of the most common implementations of the function that I ever saw.

That being said, let me go one step further and show you a simple example of how to use the previous “getMicrotime()” function inside of a benchmarking script. Here is the pertinent code sample:

$startTime=getMicrotime();

// do nothing for a while

usleep(100);

$endTime=getMicrotime();

$totalTime=$endTime-$startTime;

echo ‘Time spent in doing nothing was ‘.$totalTime.’ seconds’;

In this case, I simply applied my common sense to create a primitive PHP4-based benchmarking script. As you saw, the example first calls up the “getMicrotime()” function and stores the corresponding timestamp. Then it does nothing for a while. Finally, it displays the elapsed time via another function call. Very simple, isn’t it?

Of course, the previous example would be rather incomplete if I don’t show you the respective output generated by the above script, so here it is:

Time spent in doing nothing was 0.00837111473083 seconds

Okay, at this point, I created a fairly precise benchmarking function that can be used for timing different portions of code, or even complete applications. I do not mean that the prior example can be used freely in production environments, but it shows, in a nutshell, how easy it is to create these kind of scripts using only the “microtime()” function.

In the following section, I’ll show you how to use this helpful function with PHP 5. Thus, you can spot the difference between the different versions of the language.

To learn more on this topic, all you have to do is click on the link that appears below and read the next few lines. See you there.

{mospagebreak title=Simplifying the use of the microtime() function with PHP 5}

In the previous section, I mentioned that PHP 5 offered a slightly modified version of the native “microtime()” function, since there’s no need to create a custom function to obtain a float number from it. But you have to make sure to call this function with the “get_as_float” parameter. Then it will neatly return the corresponding timestamp as a float value.

In order to illustrate the usage of the “microtime()” function with PHP 5, I created a basic example that shows how to use this function for benchmarking purposes. Have a look a the following code sample:

// example using ‘microtime()’ function with PHP 5

$startTime=microtime(true);

// do nothing for a while

usleep(100);

$endTime=microtime(true);

$totalTime=$endTime-$startTime;

echo ‘Time spent in doing nothing was ‘.$totalTime.’ seconds’;

In this case, the above script simply calls the “microtime()” function with the “get_as_float” parameter set to true. Lastly, it displays the elapsed time as a float number. Of course, this condition is clearly demonstrated by the below output:

Time spent in doing nothing was 0.00532197952271 seconds

In addition to the example that you learned before, it’s possible to define a simple wrapper for the “microtime()” function in PHP 5 and create the following script:

// define ‘getMicrotime()’function – PHP 5

function getMicrotime(){

return microtime(true);

}

$startTime=getMicrotime();

// do nothing for a while

usleep(100);

$endTime=getMicrotime();

$totalTime=$endTime-$startTime;

echo ‘Time spent in doing nothing was ‘.$totalTime.’ seconds’;

/*

displays the following:

Time spent in doing nothing was 0.00789403915405 seconds

*/

As you can see, creating simple and effective timing scripts is something that can easily be done with PHP 4 or PHP 5, and they can be used as decent benchmarking approaches too.

So far, I demonstrated the capacity offered by PHP 4 and PHP 5 respectively for developing simple and efficient timing functions. However, it’s possible (and even desirable) to go one step further and develop an object-oriented timing approach that can be used for benchmarking purposes as well.

In this case, I’m simply talking about creating a timer class that can be utilized, obviously, to time several scripts and applications together. Therefore, I suggest you read the following section, where I’ll explain how to build these specific classes.

If creating procedural timing scripts was a no-brainer process, then you’ll probably find that building a timer class is even simpler. Basically, constructing such a class depends on defining a couple of methods that behave as basic wrappers for the built-in PHP “microtime()” function.

Considering the concepts deployed before, a typical timer class could be defined as follows:

As you can see, defining a timer class with PHP 4 is a very simple process. As I said before, all that I did here was create a wrapping method for the “microtime()” PHP native function, as well as define some additional methods that are useful for starting and stopping the corresponding timer.

Of course, this is only an introductory example and can be greatly improved. However, if you need a basic but effective timer class and don’t want to write complex code, you have one here that may fit your needs.

All right, after showing you how to create a simple timer class with PHP 4, have a look at the following example, which demonstrates how to use it:

// instantiate ‘Timer’ class

$timer=&new Timer();

// start timer

$timer->start();

// do nothing for a while

usleep(100);

// stop timer

$elapsedTime=$timer->stop();

// display elapsed time

echo ‘Time spent in doing nothing was ‘.$elapsedTime.’ seconds’;

/*

displays the following

Time spent in doing nothing was 0.00996 seconds

*/

As shown above, the entire process for timing or benchmarking a particular script is reduced to calling up the respective “start()” and “stop()” methods that belong to the “Timer” class. That’s it.

At this point, you hopefully have a clear idea of how to develop a timer class with PHP 4, since this is a no-brainer procedure that can be tackled even by beginners. Therefore, the next lesson of this tutorial will be focused on creating another handy timer class, this time using PHP 5.

Want to learn how this will be done? Jump into the following section and keep reading.

As I expressed in the section that you just read, it’s possible to define yet another timer class using the advantages offered by PHP 5 with reference to its “microtime()” function. This brand new timing class can be created as follows:

In this case, the above “Timer” class looks nearly identical to its PHP4-based counterpart. Aside from using exceptions to handle potential errors, the class in question uses a simple wrapper for the native “microtime()” function and it can be put to work as follows:

try{

// instantiate ‘Timer’ class

$timer=new Timer();

// start timer

$timer->start();

// do nothing for a while

usleep(100);

// stop timer

$elapsedTime=$timer->stop();

// display elapsed time

echo ‘Time spent in doing nothing was ‘.$elapsedTime.’ seconds’;

}

catch(Exception $e){

echo $e->getMessage();

exit();

}

The previous example is very easy to grasp. Thus, it doesn’t merit any additional discussion here. However, feel free to tweak the source code of all the classes that I showed and add your own modifications to it. You’ll have a good time!

To wrap up

In this first article of the series, I introduced the basics on how to create benchmarking scripts with PHP 4 and PHP 5. This ranged from procedural approaches to object-oriented methods. You saw that there are different options for timing your applications.

However, this journey isn’t finished yet, since in the next tutorial, I’ll show you how to use some of these classes to evaluate the performance of different PHP scripts. Don’t miss the next article!