performance.now
- Node.js course
- Intermediate
- Lesson 97/116
- 5 min
Learn high-resolution time with performance.now.
performance.now
To measure how long code takes with high resolution, use performance.now(). Unlike Date.now() it gives sub-millisecond precision; it catches small differences.
Import: const { performance } = require("node:perf_hooks");. Example: const start = performance.now(); process(); const end = performance.now(); console.log(end - start + "ms");. The difference between start and end gives the elapsed time in milliseconds. This is used for algorithm comparison, finding bottlenecks, or tracking performance regressions. performance.now() returns the time since process start; each call increases monotonically.
Measuring elapsed time
The difference between two performance.now() calls gives the elapsed time. This is the standard way to see how fast a function is.
Example: const start = performance.now(); const arr = Array(1000000).fill(0); const end = performance.now(); console.log("Time: " + (end - start) + "ms");. The output varies across machines; so tests use deterministic conditions like end >= start instead of the exact time. Taking the average of several runs gives a more reliable result. Calling performance.now() inside a loop can distort the result because of its own measurement overhead; isolate the measured code as much as possible.
Practice Measure elapsed time and print
Import with const { performance } = require("node:perf_hooks");. Start with const start = performance.now();. Create an array with const arr = Array(100).fill(0);. End with const end = performance.now();. Print with console.log("Measurement done: " + (end >= start)).
Starter code
// Import performance
// write here
// Start time
// write here
// Create an array
// write here
// End time
// write here
// Print "Measurement done: ..."
// write hereSample solution
const { performance } = require("node:perf_hooks");
const start = performance.now();
const arr = Array(100).fill(0);
const end = performance.now();
console.log("Measurement done: " + (end >= start));Expected output
Ölçüm tamam: true
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does performance.now() return?
performance.now()- A number in milliseconds Correct answer
- Bir Date nesnesi
- Bir dize
- Bir Promise
Explanation: performance.now returns a number in milliseconds.
2 Match each piece to its role
| Term | Meaning |
|---|---|
performance.now() |
High-resolution time |
node:perf_hooks |
Module name |
end - start |
Elapsed time |
Date.now() |
Millisecond count |
3 Complete the performance.now call
const start = ____();
const start = performance.now();
Explanation: performance.now gets the start time.