I just stumbled across some interesting comments in reply to a post about increasing PHP performance which suggest using the UNIX command line program "time" to provide a quick way to benchmark the performance of PHP code constructs within a terminal window.
A Couple of Examples
Here's a couple of quick tests I ran to compare the relative speed of two blocks of code which output text via the PHP "echo" command. One uses concatenation to output 3 separate strings via the "echo" command. The other echo's comma separated argument format.
time php -r "for (\$i = 0; \$i < 1000000; \$i++) echo 'Test 1'.'Test 2'.'Test 3';" > /dev/null
gave the following results:
real 0m3.393suser 0m2.064ssys 0m1.316s
time php -r "for (\$i = 0; \$i < 1000000; \$i++) echo 'Test 1','Test 2','Test 3';" > /dev/null
gave the following results:
real 0m8.232suser 0m4.225ssys 0m3.919s
Numbers displayed are in seconds. Unexpectedly, as you can see from the timings above, the sting concatenation method proves to be more efficient taking less than half the time to run.
Here's another which this time as expected shows that the "split" function, which has the overhead of regular expression matching support, is slower than "explode".
time php -r "for (\$i = 0; \$i < 1000000; \$i++) split(';', 'Test 1;Test 2;Test 3');" > /dev/null
gave the following results:
real 0m3.694suser 0m3.621ssys 0m0.027s
time php -r "for (\$i = 0; \$i < 1000000; \$i++) explode(';', 'Test 1;Test 2;Test 3');" > /dev/null
gave the following results:
real 0m1.866suser 0m1.837ssys 0m0.019s
Formatting The Output
Some versions of "time" allow you to specify an output format for the running time. The Mac version doesn't hence it's omission in the examples above.
Things To Watch
- You need to quote the PHP code.
- You need to escape any $'s and double quotes within the PHP code.
Strangely (or perhaps not) making the test case a PHP file and running it is slightly slower.
In your last example, I get the following from CLI:
And with a test.php file:
These results are consistent, too.
I guess there is some overhead in loading the file. 10 milliseconds would seem reasonable for that.
Nice example of testing the performance of your code. Will have a look at my own code, to resolve some speed issues.