Home >Web Front-end >JS Tutorial >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? 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");
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:
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!