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!


Posted

in

,

by

Comments

Leave a Reply

Discover more from The Full Stack Developer

Subscribe now to keep reading and get access to the full archive.

Continue reading