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.
blog comments powered by Disqus |
|
|
|
|
|
|
|