Home  >  Article  >  Web Front-end  >  Example of how JS uses console to calculate code running time

Example of how JS uses console to calculate code running time

韦小宝
韦小宝Original
2018-01-15 11:35:341246browse

I recently read a book and found a method for calculating code execution time. I think it is quite useful, so this article mainly introduces you to how Javascript uses console to calculate code execution time. The relevant information is introduced in great detail through js sample code. Friends who are interested in JavaScript can refer to this article.

Preface

This article mainly introduces to you the relevant content about Js using console to calculate the code running time, and shares it for your reference and study. Not much to say below, let’s take a look at the detailed introduction.

Requirements

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?

Use console.log with Dateobjectcalculation

For example, we calculate## If the #sort method takes how long it takes to sort an array of 100,000 random arrays, you can write it 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, it will be displayed on the console:

排序用时共计552ms

Below, we introduce a more flexible and accurate method.

Use console.time for time calculation

This method is more accurate than the previous one and is specifically 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.

Summary

The above is all the content of this article, I hope it can help everyone learn! !

Related recommendations:

The most complete JavaScript learning summary

How to use regular expressions to highlight JavaScript code

javascript matches the regular expression code commented in js

The above is the detailed content of Example of how JS uses console to calculate code running time. 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