How to use console to calculate code running time in js

小云云
Release: 2018-03-14 18:17:11
Original
1604 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? 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.

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:

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!

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
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!