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.

var i, output=0;    
for (i = 1; i <= 1000000; i++)
    output += i;

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.

var i, output=0 ;    
var startTime=new Date().getTime();
for (i = 1; i <= 1000000; i++)
    output += i;
var endTime=new Date().getTime();

//Time Taken : 2010ms

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()

var i, output=0;    
console.time('Addition of Million Numbers');
for (i = 1; i <= 1000000; i++)
    output += i;
console.timeEnd('Addition of Million Numbers');

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.

Leave a Reply

Your email address will not be published.

Sign Up for Our Newsletters

Get notified of the best deals on our WordPress themes.

You May Also Like
Convert A List To String In Python

Convert a list to string in Python

Table of Contents Hide Program to convert a list to string in PythonUsing join() methodUsing List ComprehensionIterating using for loopUsing map() method There are various scenarios where you would need…
View Post
Powershell Concatenate String

PowerShell Concatenate String

Table of Contents Hide Introduction to PowerShell Concatenate StringHow to Concatenate Strings and Variables in PowerShell#1. Expanding Strings#2. Substitution or string.Format approach#3 Join Operator Microsft PowerShell scripting is little different from…
View Post