Working with Performance Hooks
1. Measuring Performance (performance.now)
Example
import { performance } from "node:perf_hooks";
const t0 = performance.now();
work();
console.log("elapsed ms:", performance.now() - t0);
2. Creating Performance Marks (performance.mark)
| API | Use |
|---|---|
performance.mark("start") | Named timestamp |
performance.clearMarks(name?) | Remove |
3. Measuring Between Marks (performance.measure)
Example
performance.mark("a");
work();
performance.mark("b");
performance.measure("work", "a", "b");
4. Using Performance Observer (PerformanceObserver)
Example
import { PerformanceObserver } from "node:perf_hooks";
const obs = new PerformanceObserver((items) => {
for (const e of items.getEntries()) console.log(e.name, e.duration);
});
obs.observe({ entryTypes: ["measure", "function"] });
| entryType | Source |
|---|---|
mark / measure | User Timing API |
function | Wrapped via performance.timerify |
http / http2 | Network entries |
gc | Garbage collection |
dns | Lookups |
5. Tracking HTTP Timing
| Phase | Field |
|---|---|
| DNS | req.socket.lookupTime (estimate) |
| TCP connect | Socket "connect" event |
| TLS handshake | Socket "secureConnect" |
| TTFB | Time until response headers |
6. Monitoring Event Loop Lag
| API | Use |
|---|---|
monitorEventLoopDelay() | Histogram (min/max/percentile) |
performance.eventLoopUtilization() | Idle vs active ratio |
7. Using perf_hooks for Profiling
Example: timerify
import { performance } from "node:perf_hooks";
const wrapped = performance.timerify(slowFn);
wrapped(input);
8. Measuring Function Execution Time
| Method | Use |
|---|---|
console.time / timeEnd("label") | Quick measurement |
performance.timerify | Auto-record entries |
| Benchmark.js / mitata / tinybench | Statistical benchmarks |
9. Creating Custom Metrics
| Library | Use |
|---|---|
prom-client | Prometheus exposition format |
| OpenTelemetry SDK | Vendor-neutral metrics + traces |
10. Analyzing Performance Data
| Tool | Use |
|---|---|
| Chrome DevTools Performance | Flamecharts |
| 0x | CLI flamegraph |
| Clinic.js suite | Symptom analysis |
| Grafana / Prometheus | Long-term trends |