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");
排序用时共计552ms
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");
sort: 542.668701171875ms
string in brackets . Use the console.timeEnd method at the end and pass in the string again.
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!