How to Measure Time Taken by a Function to Execute in JavaScript

To measure the time taken by a function to execute in JavaScript, use the “performance.now()” or “console.time()” method.

Method 1: Using “performance.now()” function

You can use the performance.now() method to measure a function’s time to execute with higher precision.

Syntax

start = performance.now();
function_to_call();
end = performance.now();

Example

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.

Method 2: Using the console.time() method

To measure the time a function takes to execute in JavaScript, use the “performance.now()” or “console.time()” method.

Syntax

console.time('label');
function_to_call();
console.timeEnd('label');

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.