How to calculate the executing time of Javascript code

Spread the love

Are you looking out for the way using which you can get the executing time of Javascript code? Around the javaScript community i have seen people using various methods to achieve the same. Today i will discus various of them and also discuss which one is the better one and why.

 

Use Cases:
There are a few situations where you’d use this high resolution timer instead of grabbing a basic timestamp:

  • Benchmarking
  • game or animation runloop code
  • Calculating frame rate with precision
  • Cueing actions or audio to occur at specific points in an animation or other time-based sequence

Let’s discuss various methods of getting execution time in JavaScript.

Date() Function:

First method to get the executing time of code is using Date() function like below:

This method of getting time is not very efficient because it depends on system time. This may sometime leads to wrong results. It can also leads to negative results if user make changes in system time. So this method is not recommended.

 

console.time Method:

This method is also used to track how much time operation takes in Javascript. You can give a timer a unique name and this way you can have as much timers running on your web page.

Above method give an accuracy of milliseconds. it’s better than Date() method as it doesn’t depends on user system which can be manipulated. Also note that it is not supported by all browsers.

 

performance.now – High Resolution Timer:

This method is best one to calculate execution time as of now during writing of this article. performance.now() is a measurement of floating point milliseconds since that particular page started to load (the performance.timing.navigationStart timeStamp to be specific).

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *