Files
Backend_Assignment1/tools/performance.ts
T

62 lines
1.3 KiB
TypeScript

import { performance } from "node:perf_hooks";
type DbMetric = {
count: number;
totalMs: number;
maxMs: number;
over100Ms: number;
};
const metrics = new Map<string, DbMetric>();
export async function measureDb<T>(
label: string,
operation: () => Promise<T>,
): Promise<T> {
const started = performance.now();
try {
return await operation();
} finally {
const durationMs = performance.now() - started;
let metric = metrics.get(label);
if (!metric) {
metric = { count: 0, totalMs: 0, maxMs: 0, over100Ms: 0 };
metrics.set(label, metric);
}
metric.count++;
metric.totalMs += durationMs;
metric.maxMs = Math.max(metric.maxMs, durationMs);
if (durationMs > 100) {
metric.over100Ms++;
}
}
}
setInterval(() => {
if (metrics.size === 0) return;
const operations = Object.fromEntries(
[...metrics.entries()].map(([label, metric]) => [
label,
{
count: metric.count,
avgMs: Number((metric.totalMs / metric.count).toFixed(2)),
maxMs: Number(metric.maxMs.toFixed(2)),
over100Ms: metric.over100Ms,
},
]),
);
console.log(JSON.stringify({
type: "database_performance",
timestamp: new Date().toISOString(),
operations,
}));
metrics.clear();
}, 10_000).unref();