1. 程式人生 > >前端的一些效能測試程式碼

前端的一些效能測試程式碼

1 整個頁面載入過程時間

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script type="text/javascript">
        function performanceTest() {
            console.info("開始")
            let timing = performance.timing,
            readyStart = timing.fetchStart - timing.navigationStart,
            redirectTime = timing.redirectEnd - timing.redirectStart,
            appcacheTime = timing.domainLookupStart - timing.fetchStart,
            unloadEventTime = timing.unloadEventEnd - timing.unloadEventStart,
            lookupDomainTime = timing.domainLookupEnd - timing.domainLookupStart,
            connectTime = timing.connectEnd - timing.connectStart,
            requestTime = timing.responseEnd - timing.requestStart,
            initDomTreeTime = timing.domInteractive - timing.responseEnd,
            domReadyTime = timing.domComplete - timing.domInteractive,
            loadEventTime = timing.loadEventEnd - timing.loadEventStart,
            loadTime = timing.loadEventEnd - timing.navigationStart;
            console.log('準備新頁面時間耗時: ' + readyStart);
            console.log('redirect 重定向耗時: ' + redirectTime);
            console.log('Appcache 耗時: ' + appcacheTime);
            console.log('unload 前文件耗時: ' + unloadEventTime);
            console.log('DNS 查詢耗時: ' + lookupDomainTime);
            console.log('TCP連線耗時: ' + connectTime);
            console.log('request請求耗時: ' + requestTime);
            console.log('請求完畢至DOM載入: ' + initDomTreeTime);
            console.log('解析DOM樹耗時: ' + domReadyTime);
            console.log('load事件耗時: ' + loadEventTime);
            console.log('載入時間耗時: ' + loadTime);
        }
    </script>
</head>
<body onload="performanceTest()">

</body>
</html>

2.js程式碼段執行時間

console.profile();
// TODOS,需要測試的頁面邏輯動作
for (let i = 0; i < 100000; i++) {
    console.log(i * i);
}
console.profileEnd();

指令碼:

let timeList = [];
function addTime(tag) {
    timeList.push({
        "tag": tag,
        "time": +new Date
    });
}
addTime("loading");
timeList.push({
    "tag": "load",
    "time": +new Date()
});
// TODOS,load載入時的操作
timeList.push({
    "tag": "load",
    "time": +new Date()
});
timeList.push({
    "tag": "process",
    "time": +new Date()
});
// TODOS,process處理時的操作
timeList.push({
    "tag": "process",
    "time": +new Date()
});
parseTime(timeList); // 輸出{load: 時間毫秒數,process: 時間毫秒數}
function parseTime(time) {
    let timeStep = {},
    endTime;
    for (let i = 0, len = time.length; i < len; i++) {
        if (!time[i]) continue;
        endTime = {};
        for (let j = i + 1; j < len; j++) {
            if (time[j] && time[i].tag == time[j].tag) {
                endTime.tag = time[j].tag;
                endTime.time = time[j].time;
                time[j] = null;
            }
        }
        if (endTime.time >= 0 && endTime.tag) {
            timeStep[endTime.tag] = endTime.time - time[i].time;
        }
    }
    return timeStep;
}