Calculation of the execution time of JavaScript code

Source: Internet
Author: User

Recently read the book "High-performance JavaScript", found several methods of calculating the execution time of the code, the feeling is very useful.

We used to calculate the program, between the execution of the function, usually the time stamp before and after the execution of the code, the difference between the two is the execution time, as follows:

var count=1000; var begin=New  Date ();  for (var i=0;i<count;i++) {document.createelement ("div");} var end=New  Date (); var time=end-Begin;console.log ("Time is=" +time);

This can really show the code execution time, but to calculate the other code to repeat the timestamp, it is necessary to write an object encapsulation execution process, first create a new timer,

varTimer={data:{}, start:function(key) {Timer.data[key]=NewDate (); }, stop:function(key) {varTime=Timer.data[key]; if(Time) Timer.data[key]=NewDate ()-Time ; }, GetTime:function(){    returnTimer.data[key]; }};
Test
Timer.start ("div");
for (Var i=0;i<count;i++){
Document.createelement ("div");}
Timer.stop ("div");
Console.log ("The Time is:" +timer.gettime ());

This is the method we define, only shows the execution time, but the console of the main browser, such as Chrome, provides a way not only to display time, but also to locate a function.

The code format is as follows:

If you simply calculate the time, you can use Console.time (), the process is as follows:

Console.time ("XXX");

<code></code>

Console.timeend ("XXX");

If you need some additional performance metrics, you can use Console.profile, as follows:

Console.profile ("XX");

<code></code>

Console.profileend ("XX");

Calculation of the execution time of JavaScript code

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.