fork download
  1. <?php
  2.  
  3. $methods = array("method_diff_assoc", "method_diff_key", "method_sort");
  4.  
  5. function make_array($size) {
  6. $array = array();
  7. for ($i = 0; $i < $size; $i++) {
  8. $array[$i] = $i + 1;
  9. }
  10. shuffle($array);
  11. srand((float)microtime() * 1000000);
  12. $pos =& rand(0, $size - 1);
  13. do {
  14. $val = rand(1, $size - 1);
  15. } while ($array[$pos] == $val);
  16. $array[$pos] = $val;
  17. return $array;
  18. }
  19.  
  20. function method_diff_assoc($array) {
  21. $u = array_unique($array);
  22. $dup = array_diff_assoc($array, $u);
  23. return array_pop($dup);
  24. }
  25.  
  26. function method_diff_key($array) {
  27. $u = array_unique($array);
  28. $dup = array_diff_key($array, $u);
  29. return array_pop($dup);
  30. }
  31.  
  32. function method_sort($array) {
  33. sort($array);
  34. $prev = null;
  35. foreach ($array as $item) {
  36. if ($item === $prev) { return $item; }
  37. $prev = $item;
  38. }
  39. }
  40.  
  41. function validate($iterations) {
  42. global $methods;
  43. for ($i = 0; $i < $iterations; $i++) {
  44. $a = make_array(1000);
  45. $check = null;
  46. foreach ($methods as $method_name) {
  47. $result = call_user_func($method_name, $a);
  48. if (!is_null($check) && $check !== $result) {
  49. echo "Method $method_name returned $result instead of $check!\n";
  50. return false;
  51. }
  52. $check = $result;
  53. }
  54. }
  55. return true;
  56. }
  57.  
  58. function profile($method_name, $iterations) {
  59. $start = time();
  60. for ($i = 0; $i < $iterations; $i++) {
  61. $a = make_array(10000);
  62. call_user_func($method_name, $a);
  63. }
  64. return time() - $start;
  65. }
  66.  
  67. if (validate(20)) {
  68. echo "Tests passed, all implementations seem to argee on results.\n";
  69. } else {
  70. echo "TESTS FAILED. FIX THE CODE FIRST.\n";
  71. exit(1);
  72. }
  73. $c = 50; // Increase at will, this value is low just for ideone.com
  74. foreach ($methods as $method_name) {
  75. printf("Trying %d iterations of method %s\n", $c, $method_name);
  76. printf("\t%s took: %0.2f seconds/iteration\n", $method_name, profile($method_name, $c) / $c);
  77. }
  78.  
  79. ?>
Success #stdin #stdout 10.81s 13112KB
stdin
Standard input is empty
stdout
Tests passed, all implementations seem to argee on results.
Trying 50 iterations of method method_diff_assoc
	method_diff_assoc took: 0.08 seconds/iteration
Trying 50 iterations of method method_diff_key
	method_diff_key took: 0.10 seconds/iteration
Trying 50 iterations of method method_sort
	method_sort took: 0.02 seconds/iteration