Measure JavaScript Execution time console.time() and console.timeEnd()

Debugging the JavaScipt code to identify performance issue is a very tedious task. There are built-in JavaScript methods which you could use to measure the performance and the time taken to execute the function using console.time() and console.timeend().

Measure Javascript Execution time using console.time() and console.timeEnd()

Let’s take an example of small JavaScript function which will take some time to execute. Since most of the function will get executed in milliseconds.

The below example adds up 1 million numbers and gives the output. To get the sum of numbers it would definitely take some time by this way we could see the execution time properly.

If we need to perform this in the old traditional way then we could use JS date time and complete the task. Here is the example to measure the execution time using Date() and getTime() method.

If you are using modern browsers there is a shorthand method to perform the same task. There is a timer you could run in JavaScript to measure the execution time. Let’s take a look at the below example which uses console.time() and console.timeEnd()

If you notice the above code it is much simpler now. All you need to do is to start the timer by using console.time() and it is ended by using console.timeEnd(). The timer name passed to both the functions must match in order for measuring to work properly.

Note that console.time() and console.timeEnd() are only supported by modern browsers, starting with Chrome 2, Firefox 10, Safari 4, and Internet Explorer 11

This could be used in the development environment to quickly measure the performance of the JavaScript methods. There are much more advanced techniques which you could use for performance testing and benchmark.

You may also like...

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.