在JS中統計函數執行次數與執行時間


假如想統計JS中的函數執行次數最多的是哪個,執行時間最長的是哪個,該怎么做呢?

 

1. 統計函數執行次數

2. 統計函數執行時間

3. 如何控制函數的調用次數

4. 如何控制函數的執行時間

 

一、統計函數執行次數

常規的方法可以使用 console.log 輸出來肉眼計算有多少個輸出

不過在Chrome中內置了一個 console.count 方法,可以統計一個字符串輸出的次數。我們可以利用這個來間接地統計函數的執行次數

function someFunction() {
    console.count('some 已經執行');
}

function otherFunction() {
    console.count('other 已經執行');
}

someFunction(); // some 已經執行: 1
someFunction(); // some 已經執行: 2
otherFunction(); // other 已經執行: 1

console.count(); // default: 1
console.count(); // default: 2

不帶參數則為 default 值,否則將會輸出該字符串的執行次數,觀測起來還是挺方便的

 

當然,除了輸出次數之外,還想獲取一個純粹的次數值,可以用裝飾器將函數包裝一下,內部使用對象存儲調用次數即可

var getFunCallTimes = (function() {
    
    // 裝飾器,在當前函數執行前先執行另一個函數
    function decoratorBefore(fn, beforeFn) {
        return function() {
            var ret = beforeFn.apply(this, arguments);

            // 在前一個函數中判斷,不需要執行當前函數
            if (ret !== false) {
                fn.apply(this, arguments);
            }
        };
    }
    
    // 執行次數
    var funTimes = {};
    
    // 給fun添加裝飾器,fun執行前將進行計數累加
    return function(fun, funName) {
        // 存儲的key值
        funName = funName || fun;
        
        // 不重復綁定,有則返回
        if (funTimes[funName]) {
            return funTimes[funName];
        }
        
        // 綁定
        funTimes[funName] = decoratorBefore(fun, function() {
            // 計數累加
            funTimes[funName].callTimes++;

            console.log('count', funTimes[funName].callTimes);
        });
        
        // 定義函數的值為計數值(初始化)
        funTimes[funName].callTimes = 0;

        return funTimes[funName];
    }
})();
function someFunction() {
    
}

function otherFunction() {
    
}


someFunction = getFunCallTimes(someFunction, 'someFunction');

someFunction(); // count 1
someFunction(); // count 2
someFunction(); // count 3
someFunction(); // count 4

console.log(someFunction.callTimes); // 4



otherFunction = getFunCallTimes(otherFunction);
otherFunction(); // count 1
console.log(otherFunction.callTimes); // 1

otherFunction(); // count 2
console.log(otherFunction.callTimes); // 2

 

二、統計函數執行時間

Chrome中內置了 console.time 和 console.timeEnd 來打點計算時間

console.time();

for (var i = 0; i < 100000; ++i) {

}

console.timeEnd(); // default: 1.77197265625ms

不傳入參數的話,將以default輸出毫秒值

我們可以封裝一下,傳入函數名稱,類似上面的做法,使用裝飾器在函數執行前后進行處理

var getFunExecTime = (function() {
    
    // 裝飾器,在當前函數執行前先執行另一個函數
    function decoratorBefore(fn, beforeFn) {
        return function() {
            var ret = beforeFn.apply(this, arguments);

            // 在前一個函數中判斷,不需要執行當前函數
            if (ret !== false) {
                fn.apply(this, arguments);
            }
        };
    }

    // 裝飾器,在當前函數執行后執行另一個函數
    function decoratorAfter(fn, afterFn) {
        return function() {
            fn.apply(this, arguments);
            afterFn.apply(this, arguments);
        };
    }
    
    // 執行次數
    var funTimes = {};
    
    // 給fun添加裝飾器,fun執行前后計時
    return function(fun, funName) {
        return decoratorAfter(decoratorBefore(fun, function() {
            // 執行前
            console.time(funName);
        }), function() {
            // 執行后
            console.timeEnd(funName);
        });
    }
})();

那么調用的時候,就不需要理會如何計時了

function someFunction() {
    for (var i = 0; i < 100000; ++i) {

    }
}


function otherFunction() {
    for (var i = 0; i < 10000000; ++i) {

    }
}

someFunction = getFunExecTime(someFunction, 'someFunction');
someFunction(); // someFunction: 1.616943359375ms

otherFunction = getFunExecTime(otherFunction, 'otherFunction');
otherFunction(); // otherFunction: 18.157958984375ms

 

Chrome的Console API畢竟不是標准的,除了使用它之外,還可以選擇日期插件 Date 中的 getTime now 相關方法

然而使用Date對象來計算耗時並不正統,推薦使用標准的 performance.now

var start = performance.now();

console.time();

for (var i = 0; i < 10000000; ++i) {

}

var end = performance.now();

console.timeEnd(); // default: 23.598876953125ms

console.log(end - start); // 23.600000015459955

可以看到,它們是相差不大的

使用類似的方法,將它包裝起來以便方便調用

var getFunExecTime = (function() {
    
    // 裝飾器,在當前函數執行前先執行另一個函數
    function decoratorBefore(fn, beforeFn) {
        return function() {
            var ret = beforeFn.apply(this, arguments);

            // 在前一個函數中判斷,不需要執行當前函數
            if (ret !== false) {
                fn.apply(this, arguments);
            }
        };
    }

    // 裝飾器,在當前函數執行后執行另一個函數
    function decoratorAfter(fn, afterFn) {
        return function() {
            fn.apply(this, arguments);
            afterFn.apply(this, arguments);
        };
    }
    
    // 執行次數
    var funTimes = {};
    
    // 給fun添加裝飾器,fun執行前后計時
    return function(fun, funName) {
        funName = funName || fun;

        if (funTimes[funName]) {
            return funTimes[funName];
        }
        
        // 綁定
        funTimes[funName] = decoratorAfter(decoratorBefore(fun, function() {
            // 執行前
            funTimes[funName].timestampStart = performance.now();
        }), function() {
            // 執行后
            funTimes[funName].timestampEnd = performance.now();
            
            // 將執行耗時存入
            funTimes[funName].valueOf = function() {
                return this.timestampEnd - this.timestampStart;
            };
        });

        return funTimes[funName];
    }
})();
function someFunction() {
    for (var i = 0; i < 100000; ++i) {

    }
}


function otherFunction() {
    for (var i = 0; i < 10000000; ++i) {

    }
}

// 包裝
someFunction = getFunExecTime(someFunction);
// 執行
someFunction();
// 獲取耗時,可直接使用函數的 valueOf
console.log(+someFunction); // 2.0999999847263098

otherFunction = getFunExecTime(otherFunction, 'otherFunction');
otherFunction(); 
console.log(+otherFunction); // 21.00000000745058

 

三、如何控制函數的調用次數

也可以通過閉包來控制函數的執行次數

function someFunction() {
    console.log(1);
}

function otherFunction() {
    console.log(2);
}


function setFunCallMaxTimes(fun, times, nextFun) {
    return function() {
        if (times-- > 0) {
            // 執行函數
            return fun.apply(this, arguments);
        } else if (nextFun && typeof nextFun === 'function') {
            // 執行下一個函數
            return nextFun.apply(this, arguments);
        }
    };
}

var fun = setFunCallMaxTimes(someFunction, 3, otherFunction);

fun(); // 1
fun(); // 1
fun(); // 1
fun(); // 2
fun(); // 2

 

四、如何控制函數的執行時間

因為JS是單線程的,控制函數的執行時間相對來說挺麻煩

通過 async await yield 等異步特性,也許還是能辦到的

在React 16中的 Fiber 機制,在某種意義上是能控制函數的執行時機,得空再去看看它是怎么實現的吧


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM