To measure the time a function takes to execute in JavaScript, you can use the “console.time()” and “console.timeEnd()” methods.
Example
function mainFunc() {
console.time('mainFunc');
// code to be measured goes here
console.timeEnd('mainFunc');
}
mainFunc();
Output
mainFunc: 0.03ms
In this code, the console.time() method is called with a label of ‘mainFunc’ to start the timer. The code to be measured is then executed, and the console.timeEnd() method is called with the same label to stop the timer and output the time taken in milliseconds to the console.
The label passed to console.time() and console.timeEnd() should match; otherwise, you will encounter unexpected results.
Alternatively, you can use the “performance.now()” method to measure a function’s time to execute with higher precision.
function mainFunc() {
const t0 = performance.now();
// code to be measured goes here
const t1 = performance.now();
console.log(`myFunction took ${t1 - t0} milliseconds.`);
}
mainFunc();
Output
myFunction took 0.030916988849639893 milliseconds.
In this code, the performance.now() method is used to get high-precision timestamps before and after the code to be measured is executed.
The difference between the two timestamps is then logged to the console to output the time taken in milliseconds.

Niva Shah is a Software Engineer with over eight years of experience. She has developed a strong foundation in computer science principles and a passion for problem-solving.