W3docs

How to Measure Time Taken by a Function to Execute

Read this JavaScript tutorial and learn several fast and useful methods that are used to calculate the time taken by a function to execute in milliseconds.

In this snippet, we will suggest some methods that will show the way you can calculate the time which is taken by a function to execute in milliseconds.

performance.now()

The <kbd class="highlighted">now()</kbd> method of the performance interface will return a high-resolution timestamp when it is invoked during the work.

Javascript performance.now() method

javascript— editable

console.time()

The call to <kbd class="highlighted">console.time()</kbd> starts a timer, which is later stopped by <kbd class="highlighted">console.timeEnd()</kbd>. The timer names passed to both function calls must match in order to measure.

Javascript console.time() method

let output = "";
// Start timing now
console.time("somename");
for (let i = 1; i <= 1e6; i++) {
  output += i;
}
// ... and stop.
console.timeEnd("somename");

getTime()

The getTime() method will return the number of milliseconds. The following script takes some milliseconds to execute:

Javascript getTime() method

javascript— editable