Skip to content

Instantly share code, notes, and snippets.

@pbowyer
Last active January 21, 2024 11:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pbowyer/f0c2842e55c700a2c4c67af259a19af7 to your computer and use it in GitHub Desktop.
Save pbowyer/f0c2842e55c700a2c4c67af259a19af7 to your computer and use it in GitHub Desktop.
MODX plugin to set Server-Timing header
<?php
// Run on event onWebPagePrerender
// Comma-separated list of strings like: cache;desc="Cache Read";dur=23.2
// Expectation is duration is milliseconds
$totalTime = $modx->startTime ? sprintf("%2.2f", (microtime(true) - $modx->startTime) * 1000) : 0;
$queryTime = isset($modx->queryTime) ? sprintf("%2.2f", $modx->queryTime * 1000) : 0;
$queries = isset($modx->executedQueries) ? $modx->executedQueries : 0;
$phpTime = sprintf("%2.2f", ($totalTime - $queryTime));
$source = $modx->resourceGenerated ? "database" : "cache";
$memory = number_format(memory_get_peak_usage(true) / (1024 * 1024), 0, ".", "");
$parts = [
"total;desc=\"Total Execution Time\";dur={$totalTime}",
"php;desc=\"PHP Execution Time\";dur={$phpTime}",
"query;desc=\"Database Query Time\";dur={$queryTime}",
// I'm unclear how to best handle non-duration values
"queries;desc=\"Database Queries={$queries}\"",
"source;desc=\"Source: {$source}\"",
"memory;desc=\"Memory={$memory}MB\"",
];
$serverTiming = implode(",", $parts);
header("Server-Timing: {$serverTiming}");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment