Skip to content

Commit

Permalink
add performance benchmark metadata
Browse files Browse the repository at this point in the history
  • Loading branch information
ArrayIterator committed Oct 18, 2023
1 parent ea2ae07 commit 942400e
Showing 1 changed file with 54 additions and 0 deletions.
54 changes: 54 additions & 0 deletions src/Benchmark/Middlewares/DebuggingMiddleware.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,15 @@
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Throwable;
use function is_array;
use function memory_get_peak_usage;
use function memory_get_usage;
use function microtime;
use function preg_match;
use function preg_replace;
use function preg_replace_callback;
use function round;
use function sprintf;
use function str_contains;
use const PHP_INT_MAX;
use const PHP_INT_MIN;
Expand Down Expand Up @@ -73,6 +79,11 @@ protected function registerBenchmarkDebugBar(): void
[$this, 'printPerformance'],
priority: PHP_INT_MAX - 5
);
$manager->attach(
'jsonResponder.format',
[$this, 'printJsonPerformance'],
priority: PHP_INT_MAX - 5
);
}

if ($config->get('profiling') !== true || $config->get('debugBar') !== true) {
Expand Down Expand Up @@ -237,6 +248,7 @@ private function printPerformance(ResponseInterface $response): ResponseInterfac
) {
return $response;
}

try {
$response->getBody()->seek($response->getBody()->getSize());
} catch (Throwable) {
Expand Down Expand Up @@ -266,4 +278,46 @@ private function printPerformance(ResponseInterface $response): ResponseInterfac
$response->getBody()->write($str);
return $response;
}

private function printJsonPerformance($data)
{
$this->getManager()?->detach(
'jsonResponder.format',
[$this, 'printJsonPerformance'],
priority: PHP_INT_MAX - 5
);
if (!is_array($data)) {
return $data;
}
$container = $this->getContainer();
$config = ContainerHelper::use(Config::class, $container)?->get('environment');
$config = $config instanceof Config ? $config : new Config();

// maybe override? disabled!
if ($config->get('showPerformance') !== true) {
return $data;
}

$serverParams = $this->request?->getServerParams()??$_SERVER;
$startTime = (
$this->requestFloat
??$serverParams['REQUEST_TIME_FLOAT']
??$serverParams['REQUEST_TIME']
);
if (!isset($data['meta'])) {
$data['meta'] = [];
}
if (!is_array($data['meta'])) {
return $data;
}
$data['meta']['performance'] = [
'timing' => round(
(microtime(true) * 1000 - $startTime * 1000),
4
),
'peak_memory' => Consolidation::sizeFormat(memory_get_peak_usage(), 3),
'used_memory' => Consolidation::sizeFormat(memory_get_usage(), 3)
];
return $data;
}
}

0 comments on commit 942400e

Please sign in to comment.