Home >Web Front-end >JS Tutorial >How to use console to calculate code running time in js

How to use console to calculate code running time in js

小云云
小云云Original
2018-03-14 18:17:111731browse

If you learn the front-end for a certain period of time, you will consider performance issues. So the question is, how do we calculate the running time of a piece of code? This article mainly shares with you how to use the console to calculate the code running time in js. I hope it can help you.

Use console.log to calculate with Date object

For example, if we calculate how long it takes for the sort method to sort an array of 100,000 random numbers, we can write like this:

        var arr = [];        for(var i=0; i<100000; i++){
            arr.push(Math.random());
        }        var beginTime = +new Date();
        arr.sort();        var endTime = +new Date();
        console.log("排序用时共计"+(endTime-beginTime)+"ms");

Finally, the console will display:

排序用时共计552ms

Below, a more flexible and accurate method will be introduced.

Use console.time for time calculation

This method is more accurate than the previous one and is specially generated for performance:
Test case:

        var arr = [];
        for(var i=0; i<100000; i++){
            arr.push(Math.random());
        }
        console.time("sort");
        arr.sort();
        console.timeEnd("sort");

The console will print out:

sort: 542.668701171875ms

This method writes console.time at the beginning of the test and passes a string in brackets. Use the console.timeEnd method at the end and pass in the string again.
Personally recommend the second way.

Related recommendations:

Js example of using console to calculate code running time

The above is the detailed content of How to use console to calculate code running time in js. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn