Home > Web Front-end > JS Tutorial > body text

How to use console to calculate code running time in JS

小云云
Release: 2018-02-02 13:19:39
Original
1198 people have browsed it

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? I discovered a method to calculate the code execution time, so this article mainly introduces to you the relevant information about Javascript using the console to calculate the code execution time. The article introduces it in detail through the example code. Friends who need it can refer to it. I hope it can help everyone.

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");
Copy after login

Finally, the console will display:

排序用时共计552ms
Copy after login

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");
Copy after login

The console will print out:

sort: 542.668701171875ms
Copy after login

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:

Javascript debugging commands are more than Console.log()

Detailed explanation of Laravel's task scheduling console

How to customize the console object during the use of JS

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!