Home > Web Front-end > JS Tutorial > How Can I Efficiently Measure JavaScript Function Execution Time?

How Can I Efficiently Measure JavaScript Function Execution Time?

Barbara Streisand
Release: 2024-12-11 05:02:10
Original
225 people have browsed it

How Can I Efficiently Measure JavaScript Function Execution Time?

How to Measure Function Execution Duration

Measuring the execution time of a function can provide valuable insights into performance optimizations. There are several approaches to achieve this measurement.

Using performance.now() for Real-Time Performance Measurement

The modern approach for timing function execution is to utilize the performance.now() API. It returns the time elapsed since the start of the navigation in high-resolution milliseconds. To use it effectively:

  1. Define a start time variable: var startTime = performance.now()
  2. Execute the function whose duration you want to measure
  3. Define an end time variable: var endTime = performance.now()
  4. Calculate the execution time: console.log(Call to doSomething took ${endTime - startTime} milliseconds)

In Node.js, it's necessary to import the performance class using const { performance } = require('perf_hooks');.

Using console.time for Simple Time Measurement

The console.time method offers a straightforward way to measure execution time. However, it supports only one measurement at a time:

  1. Start the timer: console.time('doSomething')
  2. Execute the measured function: doSomething()
  3. End the timer: console.timeEnd('doSomething')

The string passed to time() and timeEnd() must match to properly stop the timer. Refer to the MDN or Node.js documentation for detailed explanations.

The above is the detailed content of How Can I Efficiently Measure JavaScript Function Execution Time?. 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