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