溫馨提示×

如何用JS監控系統資源

小樊
68
2025-05-04 15:03:02
欄目: 編程語言

在JavaScript中,你可以使用Performance API來監控系統資源,例如CPU使用率、內存使用情況等。以下是一些示例代碼,展示了如何使用Performance API來監控系統資源:

監控CPU使用率

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); // 頁面加載完成后監控

注意事項

  1. 權限問題:某些瀏覽器可能會限制對系統資源的訪問,特別是涉及到用戶隱私的資源。
  2. 性能影響:頻繁地監控系統資源可能會對頁面性能產生影響,因此需要謹慎使用。
  3. 瀏覽器兼容性Performance API在不同瀏覽器中的實現可能有所不同,需要進行兼容性檢查。

通過這些示例代碼,你可以開始監控系統的不同方面,并根據需要進行調整和擴展。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女