Home > Web Front-end > JS Tutorial > How Can I Measure the Execution Time of a JavaScript Function in Milliseconds?

How Can I Measure the Execution Time of a JavaScript Function in Milliseconds?

Mary-Kate Olsen
Release: 2024-12-16 06:16:11
Original
273 people have browsed it

How Can I Measure the Execution Time of a JavaScript Function in Milliseconds?

Measuring Execution Time of a Function

Question:

How do I determine the execution time of a function in milliseconds?

Answer:

Using performance.now()

The performance.now() API provides a high-resolution timestamp representing the time since navigation start. To measure the execution time of a function, follow these steps:

var startTime = performance.now();

doSomething(); // <---- Measured code goes between startTime and endTime

var endTime = performance.now();

console.log(`Call to doSomething took ${endTime - startTime} milliseconds`);
Copy after login

For Node.js, first import the performance class:

const { performance } = require('perf_hooks');
Copy after login

Using console.time

console.time provides a convenient way to measure execution time in the browser. Here's how to use it:

console.time('doSomething');

doSomething(); // <---- The function you're measuring time for

console.timeEnd('doSomething');
Copy after login

Note: The string passed to console.time() and console.timeEnd() must match for the timer to end correctly.

References:

  • [MDN documentation on console.time()](https://developer.mozilla.org/en-US/docs/Web/API/console/time)
  • [Node.js documentation on performance](https://nodejs.org/api/perf_hooks.html)

The above is the detailed content of How Can I Measure the Execution Time of a JavaScript Function in Milliseconds?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template