83 lines
2.6 KiB
PHP
83 lines
2.6 KiB
PHP
<?php
|
|
|
|
/*
|
|
This test file puts the SimpleRouter 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
|
|
routers and two separate arrays. The lookups are then run in two separate loops, one for each router.
|
|
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.
|
|
*/
|
|
|
|
// if there's a flag, reset the opcache
|
|
if (in_array('-f', $argv)) {
|
|
opcache_reset();
|
|
}
|
|
|
|
require_once 'tools.php';
|
|
require_once __DIR__ . '/../SimpleRouter.php';
|
|
|
|
// Blog test
|
|
$blog = sReadAndAddRoutes('blog.txt');
|
|
echoTitle("Starting blog lookups");
|
|
sRunIterations(100000, $blog);
|
|
sRunIterations(1000000, $blog);
|
|
|
|
// Github test
|
|
SimpleRouter::clearRoutes();
|
|
$github = sReadAndAddRoutes('github.txt');
|
|
echoTitle("Starting github lookups");
|
|
sRunIterations(10000, $github);
|
|
sRunIterations(100000, $github);
|
|
sRunIterations(1000000, $github);
|
|
|
|
// Big test; since simplerouter is so much slower, we'll only run the big test if the -b flag is passed
|
|
if (in_array('-b', $argv)) {
|
|
SimpleRouter::clearRoutes();
|
|
$big = sReadAndAddRoutes('big.txt');
|
|
echoTitle("Starting big lookups");
|
|
sRunIterations(10000, $big);
|
|
sRunIterations(100000, $big);
|
|
sRunIterations(1000000, $big);
|
|
}
|
|
|
|
function sReadAndAddRoutes(string $file): array
|
|
{
|
|
$array = [];
|
|
$routes = file($file);
|
|
foreach ($routes as $route) {
|
|
[$method, $path] = explode(' ', $route);
|
|
$path = trim($path);
|
|
// convert params from :param to {param}
|
|
$path = preg_replace('/:(\w+)/', '{$1}', $path);
|
|
$array[] = [$method, $path];
|
|
SimpleRouter::add($path, function() {
|
|
return true;
|
|
}, $method);
|
|
}
|
|
return $array;
|
|
}
|
|
|
|
function sRunIterations(int $iterations, array $routes) {
|
|
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] = $routes[array_rand($routes)];
|
|
// replace the params with random values
|
|
$uri = preg_replace_callback('/{(\w+)}/', function($matches) {
|
|
return $matches[1] . '-' . rand(1, 100);
|
|
}, $uri);
|
|
$res = SimpleRouter::run($uri, '', false, $method);
|
|
if ($res === 404 || $res === 405) {
|
|
echo Color::red("Failed to handle request for $uri - $res\n");
|
|
exit(1);
|
|
}
|
|
if ($i !== 0 && $i % ($interval) === 0) echoMemoryAndTime($i, $start);
|
|
}
|
|
echo "Time: " . Color::cyan(number_format(microtime(true) - $start, 10) . " s\n");
|
|
// echo the average time per request
|
|
echo "Avg/lookup: " . Color::yellow(number_format((microtime(true) - $start) / $iterations, 10) . " s\n");
|
|
echo "\n";
|
|
}
|