forked from PHP/Router
62 lines
2.0 KiB
PHP
62 lines
2.0 KiB
PHP
|
<?php
|
||
|
|
||
|
/*
|
||
|
This test fiel puts PHP's array to the test by running a million lookups on a handful of routes.
|
||
|
The routes are read from two files, blog.txt and github.txt, and added to two separate arrays.
|
||
|
The lookups are then run in two separate loops, one for each array.
|
||
|
Each lookup is timed and the memory usage is also printed out at regular intervals.
|
||
|
The requests are randomly picked from the array of routes.
|
||
|
*/
|
||
|
|
||
|
function readAndAddRoutes(string $file): array
|
||
|
{
|
||
|
$array = [];
|
||
|
$routes = file($file);
|
||
|
foreach ($routes as $route) {
|
||
|
[$method, $path] = explode(' ', $route);
|
||
|
$path = trim($path);
|
||
|
$array[] = [$method, $path, function() {
|
||
|
return true;
|
||
|
}];
|
||
|
}
|
||
|
return $array;
|
||
|
}
|
||
|
|
||
|
$blog = readAndAddRoutes('blog.txt');
|
||
|
$github = readAndAddRoutes('github.txt');
|
||
|
|
||
|
function echoMemoryAndTime(int $i, float $start) {
|
||
|
echo "($i lookups) M: " . round(memory_get_usage() / 1024, 1) . "kb - T: ". number_format(microtime(true) - $start, 10) ." seconds\n";
|
||
|
}
|
||
|
|
||
|
function runIterations(int $iterations, array $routes) {
|
||
|
echo "\n";
|
||
|
echo "===============================================================\n";
|
||
|
echo "\n";
|
||
|
echo "Running $iterations iterations\n";
|
||
|
$start = microtime(true);
|
||
|
$interval = $iterations / 10;
|
||
|
for ($i = 0; $i < $iterations; $i++) {
|
||
|
// pick a random route from the array
|
||
|
[$method, $uri, $handler] = $routes[array_rand($routes)];
|
||
|
$res = $handler();
|
||
|
if ($i !== 0 && $i % ($interval) === 0) echoMemoryAndTime($i, $start);
|
||
|
}
|
||
|
echo "Time taken: " . number_format(microtime(true) - $start, 10) . " seconds\n";
|
||
|
// echo the average time per request
|
||
|
echo "Average time per lookup: " . number_format((microtime(true) - $start) / $iterations, 10) . " seconds\n";
|
||
|
echo "\n";
|
||
|
}
|
||
|
|
||
|
echo "Starting blog lookups\n";
|
||
|
runIterations(100000, $blog);
|
||
|
runIterations(1000000, $blog);
|
||
|
|
||
|
echo "\n";
|
||
|
echo "===============================================================\n";
|
||
|
echo "\n";
|
||
|
echo "Starting github lookups\n";
|
||
|
runIterations(10000, $github);
|
||
|
runIterations(100000, $github);
|
||
|
runIterations(1000000, $github);
|