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?
If you actually want to benchmark real world code, use tools like Xdebug and XHProf.
Xdebug is great for when you're working in dev/staging, and XHProf is a great tool for production and it's safe to run it there (as long as you read the instructions). The results of any one single page load aren't going to be as relevant as seeing how your code performs while the server is getting hammered to do a million other things as well and resources become scarce. This raises another question: are you bottlenecking on CPU? RAM? I/O?
You also need to look beyond just the code you are running in your scripts to how your scripts/pages are being served. What web server are you using? As an example, I can make nginx + PHP-FPM seriously out perform mod_php + Apache, which in turn gets trounced for serving static content by using a good CDN.
The next thing to consider is what you are trying to optimise for?
The former can be helped by doing things like gzipping all resources sent to the browser, yet doing so could (in some circumstances) push you further away from the achieving the latter.
Hopefully all of the above can help show that carefully isolated 'lab' testing will not reflect the variables and problems that you will encounter in production, and that you must identify what your high level goal is and then what you can do to get there, before heading off down the micro/premature-optimisation route to hell.