How to find execution time in javascript?

Let’s say you want to find out the time the code you wrote took to run.

There is an easy way in javascript to do it.

Just use console.time() and console.timeEnd() methods.

Here is an example:



<html>
<body>
    
<script>

    let totaltime="Time taken";
    console.time(totaltime);
    alert("Hello");
    console.timeEnd(totaltime);

</script>

</body>
</html>

In the above code I am using a variable totalTime to give a label (against which the total execution time will get printed in the console )

First the method console.time(labelname) is invoked.

This is to be placed at the start of the code execution.

Once the code execution completes, use the method console.timeEnd(labelname) .

And then the execution time gets printed in the console along with the label.

I loaded the above html page and waited for few seconds before clicking “OK” in the alert thereby delaying the code execution :

After clicking OK in about 6 seconds:

It took around 6.5 seconds and the total time gets printed alongside the label “Time taken”

That’s it!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s