Full of lovely web standards information and a large helping of PHP

PHP Tip: A quick way to measure the performance of code

1 year, 1 month ago

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.

  1. time php -r "for (\$i = 0; \$i < 1000000; \$i++) echo 'Test 1'.'Test 2'.'Test 3';" > /dev/null

gave the following results:

  1. real 0m3.393s
  2. user 0m2.064s
  3. sys 0m1.316s
  1. time php -r "for (\$i = 0; \$i < 1000000; \$i++) echo 'Test 1','Test 2','Test 3';" > /dev/null

gave the following results:

  1. real 0m8.232s
  2. user 0m4.225s
  3. sys 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".

  1. time php -r "for (\$i = 0; \$i < 1000000; \$i++) split(';', 'Test 1;Test 2;Test 3');" > /dev/null

gave the following results:

  1. real 0m3.694s
  2. user 0m3.621s
  3. sys 0m0.027s
  1. time php -r "for (\$i = 0; \$i < 1000000; \$i++) explode(';', 'Test 1;Test 2;Test 3');" > /dev/null

gave the following results:

  1. real 0m1.866s
  2. user 0m1.837s
  3. sys 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.

Comments

  • 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:

    real    0m1.845s
    user    0m1.829s
    sys     0m0.014s

    And with a test.php file:

    real    0m1.855s
    user    0m1.839s
    sys     0m0.014s

    These results are consistent, too.

    Brad Wright - 15th July 2007

  • I guess there is some overhead in loading the file. 10 milliseconds would seem reasonable for that.

    Ed Eliot - 15th July 2007

  • Nice example of testing the performance of your code. Will have a look at my own code, to resolve some speed issues.

    Nieuws - 2nd August 2007

Help make this post better

Notes: Standard BBCode for links, bold, italic and code are supported. rel="nofollow" is added to all links. Your email address will never be displayed on the site.

Back to index