dev/tests/simple.php

68 lines
2.0 KiB
PHP
Raw Normal View History

<?php
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
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";
}