Statistics function execution times and execution time in JS

Source: Internet
Author: User

If you want to count the number of functions in JS, which is the longest execution time, what should be done?

1. Statistics function Execution times

2. Statistical function Execution Time

3. How to control the number of calls to a function

4. How to control the execution time of a function

I. Number of statistics function executions

Conventional methods can use the Console.log output to visually calculate how many outputs

In Chrome, however, a Console.count method is built in to count the number of times a string is output. We can use this to indirectly count the number of executions of a function.

function someFunction () {    console.count (' Some already executed ');} function otherfunction () {    console.count (' other already executed '//  Some has been executed: 1// some already performed: 2 // Other has been implemented: 1  //  default:1//  default:2

It is the default value without parameters, otherwise it will output the number of executions of the string, which is very convenient to observe.

Of course, in addition to the number of outputs, but also want to get a pure number of times, you can use the adorner to wrap the function, the internal use of objects to store the number of calls can be

varGetfuncalltimes = (function() {        //an adorner that executes another function before the current function executes    functionDecoratorbefore (FN, beforefn) {return function() {            varret = beforefn.apply ( This, arguments); //Judging from the previous function, you do not need to execute the current function            if(Ret!==false) {fn.apply ( This, arguments);    }        }; }        //Number of executions    varFuntimes = {}; //add an adorner to fun, counting and accumulating before the fun executes    return function(fun, funname) {//the stored key valueFunname = Funname | |Fun ; //does not repeat the binding, there is a return        if(Funtimes[funname]) {returnFuntimes[funname]; }                //bindingFuntimes[funname] = Decoratorbefore (fun,function() {            //count Accumulationfuntimes[funname].calltimes++; Console.log (' Count ', Funtimes[funname].calltimes);                }); //defines the value of a function as a count value (initialization)Funtimes[funname].calltimes = 0; returnFuntimes[funname]; }})();
functionsomeFunction () {}functionotherfunction () {}somefunction= Getfuncalltimes (someFunction, ' someFunction ')); someFunction (); //Count 1SomeFunction ();//Count 2SomeFunction ();//Count 3SomeFunction ();//Count 4Console.log (somefunction.calltimes);//4otherfunction=getfuncalltimes (otherfunction); Otherfunction ();//Count 1Console.log (Otherfunction.calltimes);//1otherfunction ();//Count 2Console.log (Otherfunction.calltimes);//2

second, statistical function execution time

Console.time and Console.timeend are built into chrome to calculate time

console.time ();  for (var i = 0; i < 100000; ++//  default:1.77197265625ms

If the parameter is not passed in, the millisecond value will be output with default

We can encapsulate, pass in the function name, similar to the above practice, use the adorner before and after the function execution processing

varGetfunexectime = (function() {        //an adorner that executes another function before the current function executes    functionDecoratorbefore (FN, beforefn) {return function() {            varret = beforefn.apply ( This, arguments); //Judging from the previous function, you do not need to execute the current function            if(Ret!==false) {fn.apply ( This, arguments);    }        }; }    //adorner, executing another function after the current function executes    functiondecoratorafter (FN, AFTERFN) {return function() {fn.apply ( This, arguments); Afterfn.apply ( This, arguments);    }; }        //Number of executions    varFuntimes = {}; //add an adorner to fun and fun to perform before and after timing    return function(fun, funname) {returnDecoratorafter (Decoratorbefore (fun,function() {            //before executionConsole.time (funname); }), function() {            //after executionconsole.timeend (funname);    }); }})();

So when it's called, there's no need to bother about timing.

functionsomeFunction () { for(vari = 0; I < 100000; ++i) {}}functionotherfunction () { for(vari = 0; i < 10000000; ++i) {}}somefunction= Getfunexectime (someFunction, ' someFunction ')); someFunction (); //somefunction:1.616943359375msotherfunction= Getfunexectime (otherfunction, ' otherfunction ')); otherfunction (); //otherfunction:18.157958984375ms

Chrome's console API is not standard after all, in addition to using it, you can also choose the date plug-in GetTime now correlation method

However, using the Date object to calculate time-consuming is not Orthodox, it is recommended to use the standard Performance.now

var start = performance.now (); Console.time ();  for (var i = 0; i < 10000000; + +i) {} var end =//  default:23.598876953125ms//  23.600000015459955

As you can see, they're not quite the difference.

Use a similar method to wrap it up for easy invocation

varGetfunexectime = (function() {        //an adorner that executes another function before the current function executes    functionDecoratorbefore (FN, beforefn) {return function() {            varret = beforefn.apply ( This, arguments); //Judging from the previous function, you do not need to execute the current function            if(Ret!==false) {fn.apply ( This, arguments);    }        }; }    //adorner, executing another function after the current function executes    functiondecoratorafter (FN, AFTERFN) {return function() {fn.apply ( This, arguments); Afterfn.apply ( This, arguments);    }; }        //Number of executions    varFuntimes = {}; //add an adorner to fun and fun to perform before and after timing    return function(fun, funname) {funname= Funname | |Fun ; if(Funtimes[funname]) {returnFuntimes[funname]; }                //bindingFuntimes[funname] = Decoratorafter (Decoratorbefore (fun,function() {            //before executionFuntimes[funname].timestampstart =Performance.now (); }), function() {            //after executionFuntimes[funname].timestampend =Performance.now (); //the execution time is savedFuntimes[funname].valueof =function() {                return  This. Timestampend- This. Timestampstart;        };        }); returnFuntimes[funname]; }})();
functionsomeFunction () { for(vari = 0; I < 100000; ++i) {}}functionotherfunction () { for(vari = 0; i < 10000000; ++i) {}}//PackagingSomeFunction =Getfunexectime (someFunction);//ExecutionsomeFunction ();//get time-consuming valueOf that can be used directly with functionsConsole.log (+somefunction);//2.0999999847263098otherfunction= Getfunexectime (otherfunction, ' otherfunction ')); otherfunction (); Console.log (+otherfunction);//21.00000000745058

third, how to control the number of calls to the function

You can also control how many times a function executes by closing a packet.

functionsomeFunction () {Console.log (1);}functionotherfunction () {Console.log (2);}functionsetfuncallmaxtimes (fun, Times, Nextfun) {return function() {        if(times--> 0) {            //Execute function            returnFun.apply ( This, arguments); } Else if(Nextfun &&typeofNextfun = = = ' function ') {            //executes the next function            returnNextfun.apply ( This, arguments); }    };}varFun = Setfuncallmaxtimes (someFunction, 3, otherfunction); fun (); //1Fun ();//1Fun ();//1Fun ();//2Fun ();//2

Iv. How to control the execution time of functions

Because JS is single-threaded, the execution time of the control function is relatively troublesome

Async await yield and other asynchronous features, maybe you can do it.

In react 16, the Fiber mechanism, in a sense, is able to control the execution of the function of the time, hollow to see how it is realized.

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.