Intermediate LevelNode JS
How do you measure execution latency and HTTP metrics using the node:perf_hooks module?
❓ Interview Prompt: Explain `node:perf_hooks`, `performance.now()`, `performance.mark()`, `performance.measure()`, and `PerformanceObserver`.
The 'node:perf_hooks' module provides high-resolution performance monitoring matching the W3C User Timing specification:
•
'performance.now()': Returns high-resolution timestamp in milliseconds.
•
'performance.mark(label)' / 'measure(name, start, end)': Measures execution latency between code checkpoints.
•
'PerformanceObserver': Collects performance metrics asynchronously without polluting application logic.
Code Implementation Example
javascript
import { performance, PerformanceObserver } from 'node:perf_hooks';
const obs = new PerformanceObserver((items) => {
items.getEntries().forEach((entry) => {
console.log('${entry.name}: ${entry.duration.toFixed(2)}ms');
});
});
obs.observe({ entryTypes: ['measure'] });
performance.mark('start:db');
setTimeout(() => {
performance.mark('end:db');
performance.measure('Database Execution Time', 'start:db', 'end:db');
}, 100);💡Measuring execution latency using node:perf_hooks.
🎯 Interview Key Takeaway
Use node:perf_hooks PerformanceObserver for precise high-resolution performance benchmarking.
#perf_hooks#Performance#Metrics#Benchmarking#Intermediate
Back to all Node JS Questions→