I want to know what is the best way to benchmark my PHP scripts. Does not matter if a cron job, or webpage or web service.
I know i can use microtime but is it really giving me the real time of a PHP script?
I want to test and benchmark different functions in PHP that do the same thing. For example, preg_match
vs strpos
or domdocument
vs preg_match
or preg_replace vs str_replace`
Example of a webpage:
<?php
// login.php
$start_time = microtime(TRUE);
session_start();
// do all my logic etc...
$end_time = microtime(TRUE);
echo $end_time - $start_time;
This will output: 0.0146126717 (varies all the time - but that is the last one I got). This means it took 0.015 or so to execute the PHP script.
Is there a better way?
Put it in a
for
loop to do each thing 1,000,000 times to get a more realistic number. And only start the timer just before the code you actually want to benchmark, then record the end time just after (i.e. don't start the timer before thesession_start()
.Also make sure the code is identical for each function you want to benchmark, with the exception of the function you are timing.
How the script is executed (cronjob, php from commandline, Apache, etc.) should not make a difference since you are only timing the relative difference between the speed of the different functions. So this ratio should remain the same.
If the computer on which you are running the benchmark has many other things going on, this could affect the benchmark results if there happens to be a spike in CPU or memory usage from another application while your benchmark is running. But as long as you have a lot of resources to spare on the computer then I don't think this will be a problem.
It is also good to keep your eyes on your PHP code and cross check with this link , in order to make sure that your coding itself is not potentially disturbing the performance of the app.
Try https://github.com/fotuzlab/appgati
It allows to define steps in the code and reports time, memory usage, server load etc between two steps.
Something like:
Sample output array: