Script for benchmarking PHP functions

Often I find myself needing to know which way of performing a task in PHP is the fastest. The code below let's you easily test snippets of code to see how long it takes to run.

PHP:
  1. /*  Set up variables  */
  2. $testcount = 10;
  3. $iterations = 100000;
  4. for ($x=0;$x<$testcount;$x++)
  5. {
  6. $starttime = microtime();
  7. for ($i=0;$i<$iterations;$i++)
  8. {
  9. /*************************
  10. The test code goes in here
  11. *************************/
  12. }
  13. $endtime = microtime();
  14. $starttime = explode(" ", $starttime);
  15. $starttime = $starttime[1] + $starttime[0];
  16. $endtime = explode(" ", $endtime);
  17. $endtime = $endtime[1] + $endtime[0];
  18. $timerecord[$x] = ($endtime - $starttime);
  19. }
  20. echo "\n";
  21. echo "Test completed\n";
  22. echo "   Test count: ".(number_format($testcount))."\n";
  23. echo "   Iterations: ".(number_format($iterations))."\n";
  24. echo "Results:\n";
  25. for ($q=0;$q<count($timerecord);$q++)
  26. {
  27. echo "   Time ".($q+1)." = ".$timerecord[$q]." seconds (".(number_format($timerecord[$q] / $iterations, 15)).")\n";
  28. }

To test your snippet just place it between the brackets on lines 9-11. As it's written it will run whatever code you enter 1,000,000 times - 100,000 iterations 10 times. That may be way too many so lines 2 and 3 let you determine how many tests and how many iterations in each test.

I've used this code to run quite a few benchmarks and will be posting a few of them here as I get a chance.

Question, Comments...

Do you have more questions. Please either leave a comment below or join us in our new forum.

One Response to “Script for benchmarking PHP functions”

  1. [...] benchmarking code I’m starting with the benchmarking script I wrote about earlier. It seems to be fairly easy to use and get data quickly. That post is just a framework though. [...]

Leave a Reply