The perf_hooks module provides precise performance timing APIs similar to browser Performance APIs. Here's how to use it.
Basic Timing#
Performance Marks and Measures#
PerformanceObserver#
Timing Functions#
HTTP Server Timing#
Histogram for Statistics#
Resource Timing#
Custom Performance Entries#
Performance Timeline#
Profiling Middleware#
Benchmark Utility#
Best Practices#
Measurement:
✓ Use marks and measures
✓ Name entries descriptively
✓ Clear entries after collection
✓ Use PerformanceObserver for async
Accuracy:
✓ Warmup before benchmarking
✓ Multiple iterations
✓ Calculate percentiles
✓ Account for GC pauses
Production:
✓ Sample measurements
✓ Aggregate statistics
✓ Monitor percentiles (p95, p99)
✓ Set alerting thresholds
Avoid:
✗ Too many performance marks
✗ Forgetting to clear entries
✗ Blocking with analysis
✗ Ignoring outliers
Conclusion#
The perf_hooks module provides powerful tools for precise performance measurement in Node.js. Use marks and measures for timing code sections, PerformanceObserver for async monitoring, and histograms for statistical analysis. Implement timing middleware for HTTP servers and build benchmark utilities for comparing implementations. Remember to clear entries to prevent memory growth and sample in production to minimize overhead.