Tuesday, June 16, 2009 - 文章

CODE-Javascript測速用碼錶

前陣子我分享了關於JS效能調校的經驗,IE8 Dev Tool是個很方便的工具。不過,不是每種瀏覽器上都有Profiler可用,若想在不同瀏覽器上都能精確地量測某段操作的時間長短,寫一個Javascript版的Stopwatch計時碼錶應是最直接有效的方法。所以我寫了一個JS計時碼錶---darkStopWatch:

//Declare a stopWatch "class"
function darkStopWatch(timerName) {
    this.timerName = timerName;
    this.timerSt = new Date();
    this.resultQueue = [];
    this.tag = "Test";
}
darkStopWatch.prototype = {
    start: function(tag) {
        this.tag = tag;
        this.timerSt = new Date();
    },
    stop: function() {
        var ts = new Date() - this.timerSt;
        this.resultQueue.push(this.tag + " -> " + ts + "ms");
    },
    getRecord: function(clear) {
        var s = this.resultQueue.join("\n");
        if (clear) this.clear();
        return "StopWatch [" + this.timerName + 
               "]\n====================\n" + s;
    },
    reset: function() {
        this.resultQueue = [];
    }
}

使用方法還蠻簡單的,利用new darkStopWatch("碼錶標籤")宣告物件,用start(“計時標籤")開始計時、stop()停止計時,darkStopWatch會將start()到stop()的時間記錄為該"計時標籤"的時間長度,並可反覆多次start()/stop(),最後則是用getRecord()取回所有計時結果。

以下的範例有三段,第一段是計算你按下alert確認鈕的時間長度、第二段是連續五次計時,每次長度為1秒,第三段則是示範一次可以使用多個碼錶。Check it out!

//Usage
var sw = new darkStopWatch("Alert Delay");
sw.start();
alert("請等待幾秒鐘再按下確定");
sw.stop();
alert(sw.getRecord());
 
//Use setTimeout go test the measure unit
function measure() {
    var sw = new darkStopWatch("歸零射擊");
    sw.start("Test 1");
    var count = 1;
    var hnd = setInterval(
        function() {
            sw.stop();
            if (count < 5) {
                count++;
                sw.start("Test " + count);
            }
            else {
                clearInterval(hnd);
                alert(sw.getRecord());
            }
        },
    1000);
    //Demo 2, multiple stopwatches
    window.swAry = [];
    for (var i = 1; i <= 5; i++) {
        swAry[i] = new darkStopWatch("Swatch " + i);
        swAry[i].start("Wait for " + i + " sec");
        setTimeout("swAry[" + i + "].stop()", i * 1000);
    }
    setTimeout(function() {
        for (var i = 1; i <= 5; i++)
            alert(swAry[i].getRecord());
    }, 6000);
}
measure();
        

搜尋

Go

<June 2009>
SunMonTueWedThuFriSat
31123456
78910111213
14151617181920
21222324252627
2829301234
567891011
 
RSS
【工商服務】
最新回應

Tags 分類檢視
關於作者

一個醉心技術又酷愛分享的Coding魔人,十年的IT職場生涯,寫過系統、管過專案, 也帶過團隊,最後還是無怨無悔地選擇了技術鑽研這條路,近年來則以做一個"有為的中年人"自許。

文章典藏
其他功能

這個部落格


BlogLook Score and Rank

Syndication