<?php
/**
* Collection Performance Measurement Tool
*
* Measures the performance of different collection types in PHP.
* Uses a configuration file to define collections to test and number of iterations.
*/
// Configuration file path
define('CONFIG_FILE', 'config.ini');
/**
* Loads the configuration from the config file.
*
* @return array An associative array containing the configuration parameters.
*/
function loadConfig() {
$config = [];
if (file_exists(CONFIG_FILE)) {
$config = parse_ini_file(CONFIG_FILE);
}
return $config;
}
/**
* Measures the performance of a given collection type.
*
* @param string $collectionType The type of collection to measure (e.g., 'array', 'stdClass', 'array_multisort').
* @param int $iterations The number of iterations to perform.
* @return float The average execution time in milliseconds.
*/
function measureCollectionPerformance(string $collectionType, int $iterations = 10000) {
$startTime = microtime(true);
switch ($collectionType) {
case 'array':
$collection = [];
for ($i = 0; $i < $iterations; $i++) {
$collection = array_map(function($x) { return $x * 2; }, range(1, 100));
}
break;
case 'stdClass':
$collection = new stdClass();
for ($i = 0; $i < $iterations; $i++) {
$collection->value = $i;
}
break;
case 'array_multisort':
$collection = [];
for ($i = 0; $i < $iterations; $i++) {
$collection = array_multisort(range(1, 100), range(1, 100));
}
break;
default:
return 0; // Return 0 for unsupported collection types
}
$endTime = microtime(true);
return ($endTime - $startTime) * 1000 / $iterations; // Calculate average time in milliseconds
}
/**
* Main function to run the performance tests.
*/
function main() {
$config = loadConfig();
if (!isset($config['collections'])) {
die("Error: 'collections' section not found in config.ini");
}
foreach ($config['collections'] as $collectionType => $iterations) {
if (!is_numeric($iterations) || $iterations <= 0) {
continue; // Skip if iterations is not a positive number
}
$avgTime = measureCollectionPerformance($collectionType, $iterations);
echo "Collection Type: $collectionType, Average Time: " . number_format($avgTime, 4) . " ms\n";
}
}
// Run the main function
if (PHP_SAPI === 'cli') {
main();
}
?>
Add your comment