Measuring The Speed Of PHP Scripts
Measuring the speed of your PHP script is quite simple & I’ve seen a lot of different implementations of it in my time as a PHP developer, here is a version that I have stuck with & find works the best.
At the start of your script simply place this:
1 |
$s = microtime(true); |
Then at end of your script place:
1 2 |
$e = microtime(true); echo round($e - $s, 2) . " Sec"; |
Now I’m pretty sure someone else uses exactly the same code, but this is the code that I use to measure the speed of my scripts.
It really is that simple. Normally you would leave the second parameter of round()
as it is, but if you find that your script reports the time as ‘0 Sec’ increase the number until you get an answer.
There is one thing to note. If you have to increase the decimal places above a certain amount (around 5 or 6) you might get an answer such as 3.5E-5
it can be a little confusing if you are not familiar with scientific notation. Basically ‘E’ is an exponent code, and is similar (if not the same) as ‘to the power’. So 3.5E-5 translates to 0.000035. So the number after the ‘E’ indicates how many 0s to add, however because it is a negative you add all except the first zero after the decimal point. I hope that makes sense, I never was very good at explaining mathematics.
Another use for this is measuring sections of a script. You can place the $s
& $e
variables anywhere and it will measure the time it takes to execute the code between them. Handy. 🙂
I hope this quick tip has helped you. Let me know if you have any little snippets of code you like to use to measure script performance that you’d like to share.