To measure the time taken by a function to execute in JavaScript, you can use the following methods:
1. Using console.time()
and console.timeEnd()
Ideal for quick debugging during development.
Example:
console.time("myFunction");
myFunction(); // Function to measure
console.timeEnd("myFunction");
// Output: "myFunction: 12.345ms"
2. Using performance.now()
(High Precision)
Provides sub-millisecond resolution and is not affected by system clock changes.
Example:
const start = performance.now();
myFunction();
const duration = performance.now() - start;
console.log(`Time: ${duration} milliseconds`);
Note:
- Browser: Supported natively.
- Node.js: Use
require('perf_hooks').performance
.
3. Using Date.now()
(Millisecond Precision)
Simpler but less precise than performance.now()
.
Example:
const start = Date.now();
myFunction();
const duration = Date.now() - start;
console.log(`Time: ${duration} ms`);
Handling Asynchronous Functions
For async
/Promise
-based functions, measure time inside the callback:
Example:
const start = performance.now();
myAsyncFunction()
.then(() => {
const duration = performance.now() - start;
console.log(`Async time: ${duration} ms`);
});
Using async/await
:
async function measureAsync() {
const start = performance.now();
await myAsyncFunction();
const duration = performance.now() - start;
console.log(`Time: ${duration} ms`);
}
Key Differences
Method | Precision | Use Case | Notes |
---|---|---|---|
console.time | ~1ms | Quick debugging | Labels required |
performance.now | Microseconds | Accurate performance metrics | Avoid for cross-browser timing attacks |
Date.now | 1ms | Simple timing | Affected by system clock |
Example Workflow
// Synchronous function
function calculateSum() {
let sum = 0;
for (let i = 0; i < 1e6; i++) sum += i;
return sum;
}
// Measure execution time
const start = performance.now();
calculateSum();
const time = performance.now() - start;
console.log(`Calculation took ${time.toFixed(2)} ms`);
Best Practices
- Use
performance.now()
for benchmarking. - Wrap asynchronous code in
async/await
or.then()
for accurate timing. - Avoid measuring extremely short functions (<1ms) with
Date.now()
due to low precision.
By choosing the right method, you can accurately measure function execution time in any JavaScript environment!