Easier Benchmarking in your PHP Scripts

One thing I often find myself doing, whether I am testing the performance of a script, or finding the fastest function to use, is taking and outputting various time intervals throughout my script. Although this is an easy task in PHP, I thought it would be worth developing a class to give me a better experience in this situation.

The idea of using this class is simple. When you want to start Benchmarking your PHP script, you initialise the class, and you call the addBenchmark() method to take a benchmark time. You can optionally pass in a name of the benchmark. When your PHP script enters shutdown the benchmark times will be output, or you can optionally call the outputTimes() method to output them earlier. A simple example of usage is below:

Code

Output

I’d just like to go over some features of the class. The first is how to make the output function execute on shutdown in PHP. The code for the constructor is below:

 

The PHP Source Code

 

The constructor takes a boolean value, and uses this in the if statement at the start of the constructor. The line of code that is executed if this is true is the interesting one. PHP has a function called register_shutdown_function, which allows us to pass in a function to execute once our script has finished executing. This is extremely useful as it means that I can set my class to automatically output my times at the end of my script, perfect for debugging as it minimizes the amount of extra code I have to write for debugging purposes.

The other key thing to note here, is usually you pass in the name of the function you want to call as a string. However PHP also provides this helpful alternative, that lets me pass in an object, and the string of the name of the method I want to call on that object in an array. I do this by passing in $this, to pass in the current object. This means I can call a method of my class on shutdown, rather than a global function.

The full source code is below. I welcome any comments on possible improvements to the class. As you can see the rest of the code is fairly simple, but feel free to ask any questions you may have that I haven’t already answered in this post.

 

Source

 

Leave a Reply