Benchmark function for php


/ Published in: PHP
Save to your folder(s)



Copy this code and paste it in your HTML
  1. <?php
  2. /*
  3. * Function: benchmark
  4. * Author: Michael Bailey <[email protected]>
  5. * Date: 5 Dec 2002
  6. * License: GPL (General Public License)
  7. * Purpose: This function will run the line of code
  8. * sent as the first parameter and return
  9. * the time it took to complete execution.
  10. * If a second parameter is passed, the
  11. * function will run the code the specified
  12. * number of times, taking the average. This
  13. * will return a better approximation. The
  14. * last parameter allows you to send code to
  15. * be executed between iterations, in case
  16. * something needs to be reset (ie. global
  17. * variables, etc...). The function returns
  18. * the number of seconds
  19. * with a bunch of decimal places.
  20. */
  21. function benchmark($code, $iter = 1, $reset_code = null)
  22. {
  23. # Determine the overhead in calling the eval function
  24. # You might want to to this multiple times to get better
  25. # precision.
  26. $start = microtime();
  27. eval("");
  28. $end = microtime();
  29. list($start_ms, $start_s) = explode(" ", $start);
  30. list($end_ms, $end_s) = explode(" ", $end);
  31. $overhead = ($end_ms+$end_s) - ($start_ms+$start_s);
  32.  
  33. # Execute the code the specified number of times
  34. for ($i=0; $i<$iter; $i++) {
  35. $start = microtime();
  36. eval($code);
  37. $end = microtime();
  38. list($start_ms, $start_s) = explode(" ", $start);
  39. list($end_ms, $end_s) = explode(" ", $end);
  40. $time += ($end_ms+$end_s) - ($start_ms+$start_s);
  41.  
  42. # If reset code was specified, evaluate it
  43. if ($reset_code != null) eval($reset_code);
  44. }
  45.  
  46. # Return the average speed subtracted by
  47. # the overhead of calling eval()
  48. return ($time/$iter) - $overhead;
  49. }
  50. ?>

URL: http://www.codewalkers.com/c/a/Miscellaneous-Code/Quick-n-Easy-Benchmark/

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.