Home > Article > Web Front-end > How to use console to calculate code running time in js
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.
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.
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!