perf_hooks
- Node.js course
- Advanced
- Lesson 13/83
- 5 min
Learn performance measurement with perf_hooks.
What is perf_hooks?
perf_hooks is Node.js's built-in performance measurement module. It implements the W3C Performance Timeline standard, so it works much like the browser performance API.
It offers two core tools: performance.now() gives a high-resolution timestamp; PerformanceObserver catches performance entries (PerformanceEntry) live. The module is built in: you import it with require("perf_hooks").
performance.now vs Date.now
Date.now() gives milliseconds since the Unix epoch; but its resolution is a millisecond and it depends on the system clock. performance.now() gives time since process start with microsecond precision.
To measure how long a piece of code takes: take performance.now() at the start, again at the end, and compute the difference. This is the foundation of benchmarking and optimization work.
Practice Log the type of now
Import performance from perf_hooks. Log typeof performance.now.
Starter code
// import the module, get the timer
// log the type of nowSample solution
const { performance } = require("perf_hooks");
console.log(typeof performance.now);Expected output
function
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does performance.now() return?
- A number in milliseconds Correct answer
- Bir Promise
- Bir tarih dizesi
- Bir Buffer
Explanation: performance.now() returns a high-resolution number in milliseconds.
2 Complete the module name
const { performance } = require("____")
const { performance } = require("perf_hooks")
Explanation: The perf_hooks module loads as 'perf_hooks'.
3 Match each piece to its role
| Term | Meaning |
|---|---|
perf_hooks |
Performance module |
performance.now() |
Measures time |
PerformanceObserver |
Catches entries |
performance |
Timer |