1. <?php
  2. /**
  3. * Collection Performance Measurement Tool
  4. *
  5. * Measures the performance of different collection types in PHP.
  6. * Uses a configuration file to define collections to test and number of iterations.
  7. */
  8. // Configuration file path
  9. define('CONFIG_FILE', 'config.ini');
  10. /**
  11. * Loads the configuration from the config file.
  12. *
  13. * @return array An associative array containing the configuration parameters.
  14. */
  15. function loadConfig() {
  16. $config = [];
  17. if (file_exists(CONFIG_FILE)) {
  18. $config = parse_ini_file(CONFIG_FILE);
  19. }
  20. return $config;
  21. }
  22. /**
  23. * Measures the performance of a given collection type.
  24. *
  25. * @param string $collectionType The type of collection to measure (e.g., 'array', 'stdClass', 'array_multisort').
  26. * @param int $iterations The number of iterations to perform.
  27. * @return float The average execution time in milliseconds.
  28. */
  29. function measureCollectionPerformance(string $collectionType, int $iterations = 10000) {
  30. $startTime = microtime(true);
  31. switch ($collectionType) {
  32. case 'array':
  33. $collection = [];
  34. for ($i = 0; $i < $iterations; $i++) {
  35. $collection = array_map(function($x) { return $x * 2; }, range(1, 100));
  36. }
  37. break;
  38. case 'stdClass':
  39. $collection = new stdClass();
  40. for ($i = 0; $i < $iterations; $i++) {
  41. $collection->value = $i;
  42. }
  43. break;
  44. case 'array_multisort':
  45. $collection = [];
  46. for ($i = 0; $i < $iterations; $i++) {
  47. $collection = array_multisort(range(1, 100), range(1, 100));
  48. }
  49. break;
  50. default:
  51. return 0; // Return 0 for unsupported collection types
  52. }
  53. $endTime = microtime(true);
  54. return ($endTime - $startTime) * 1000 / $iterations; // Calculate average time in milliseconds
  55. }
  56. /**
  57. * Main function to run the performance tests.
  58. */
  59. function main() {
  60. $config = loadConfig();
  61. if (!isset($config['collections'])) {
  62. die("Error: 'collections' section not found in config.ini");
  63. }
  64. foreach ($config['collections'] as $collectionType => $iterations) {
  65. if (!is_numeric($iterations) || $iterations <= 0) {
  66. continue; // Skip if iterations is not a positive number
  67. }
  68. $avgTime = measureCollectionPerformance($collectionType, $iterations);
  69. echo "Collection Type: $collectionType, Average Time: " . number_format($avgTime, 4) . " ms\n";
  70. }
  71. }
  72. // Run the main function
  73. if (PHP_SAPI === 'cli') {
  74. main();
  75. }
  76. ?>

Add your comment