在JavaScript中,你可以使用Performance API來監控系統資源,例如CPU使用率、內存使用情況等。以下是一些示例代碼,展示了如何使用Performance API來監控系統資源:
function monitorCpuUsage() {
const performanceData = window.performance.now();
const cpuUsage = (performanceData - lastPerformanceData) / 1000; // 計算時間間隔(秒)
lastPerformanceData = performanceData;
console.log(`CPU Usage: ${cpuUsage} seconds`);
}
let lastPerformanceData = window.performance.now();
setInterval(monitorCpuUsage, 1000); // 每秒監控一次
function monitorMemoryUsage() {
const memoryUsage = window.performance.memory.usedJSHeapSize;
console.log(`Memory Usage: ${memoryUsage} bytes`);
}
setInterval(monitorMemoryUsage, 1000); // 每秒監控一次
function monitorNetworkRequests() {
const networkRequests = window.performance.getEntriesByType('resource');
console.log(`Total Network Requests: ${networkRequests.length}`);
}
setInterval(monitorNetworkRequests, 1000); // 每秒監控一次
function monitorPageLoadTime() {
const loadTime = window.performance.timing.loadEventEnd - window.performance.timing.navigationStart;
console.log(`Page Load Time: ${loadTime} milliseconds`);
}
window.addEventListener('load', monitorPageLoadTime); // 頁面加載完成后監控
Performance API在不同瀏覽器中的實現可能有所不同,需要進行兼容性檢查。通過這些示例代碼,你可以開始監控系統的不同方面,并根據需要進行調整和擴展。