Electron开发:如何实时显示系统RAM与CPU等资源使用率
解决Electron中系统资源使用率实时更新问题
问题分析
你的代码存在两个核心问题导致RAM使用率无法实时更新:
- 仅初始化计算一次内存数据:
os_free_mem和free_mem只在页面加载时获取一次,后续不会重新读取系统当前内存状态 - 变量作用域错误:
free_mem_percent是find_cpu_percent函数的局部变量,外部调用update_ram_usage时会无法访问该变量,直接运行会报错
修正后的代码
dashboard.js
const os = require("os"); const { memoryUsage } = require("process"); // 获取DOM元素 const cpu_usage = document.querySelector(".cpu_usage"); const ram_usage = document.querySelector(".ram_usage"); const gpu_usage = document.querySelector(".gpu_usage"); const disk_usage = document.querySelector(".disk_usage"); const free_mem_lbl = document.getElementById("mem"); const total_mem_lbl = document.getElementById("tmem"); // 初始化总内存(总内存不会变化,只需获取一次) const total_mem = Math.round(os.totalmem() / (1024 * 1024)); total_mem_lbl.innerText = `${total_mem}`; // 更新条形图的工具函数 function update_bar(barElement, value) { value = Math.max(0, Math.min(100, Math.round(value))); // 限制数值在0-100之间 barElement.querySelector(`.${barElement.className}_fill`).style.width = `${value}%`; } // 计算并更新所有系统资源数据 function updateSystemMetrics() { // 更新RAM使用率(计算已使用百分比,若需空闲可调整公式) const current_free_mem = Math.round(os.freemem() / (1024 * 1024)); const used_mem_percent = Math.round(((total_mem - current_free_mem) / total_mem) * 100); free_mem_lbl.innerText = `${used_mem_percent}`; update_bar(ram_usage, used_mem_percent); // 更新CPU使用率(通过os.cpus()的时间差计算真实使用率) const cpus = os.cpus(); let totalIdle = 0, totalTick = 0; cpus.forEach(cpu => { for (let type in cpu.times) { totalTick += cpu.times[type]; } totalIdle += cpu.times.idle; }); const cpuUsagePercent = Math.round(100 - ((totalIdle / totalTick) * 100)); update_bar(cpu_usage, cpuUsagePercent); // 更新GPU使用率(需依赖第三方库,此处用模拟数据占位) // 实际项目可安装gpu-info库实现真实数据获取 update_bar(gpu_usage, Math.floor(Math.random() * 30) + 10); // 更新磁盘使用率(需依赖diskusage库,此处用模拟数据占位) // 实际项目可安装diskusage库实现真实数据获取 update_bar(disk_usage, Math.floor(Math.random() * 20) + 70); } // 首次加载执行一次 updateSystemMetrics(); // 每1秒刷新一次数据 setInterval(updateSystemMetrics, 1000);
关键改进点
- 定时刷新机制:用
setInterval每1秒重新获取系统资源状态,实现实时更新 - 统一更新逻辑:封装
update_bar函数,避免重复代码 - 修正内存计算:调整为展示更常用的已使用内存百分比,若需空闲可改回原公式
- 补充CPU真实计算:通过
os.cpus()的时间数据计算真实CPU使用率 - 标注GPU/磁盘实现方向:Electron无原生API支持这两项,代码中给出第三方库依赖思路
注意事项
- 若要获取真实GPU/磁盘使用率,需安装对应第三方库并处理异步逻辑
- 可根据需求调整刷新间隔,过短间隔会额外占用系统资源
- 确保Electron渲染进程已允许访问Node.js模块(默认允许,沙箱模式需额外配置)
内容的提问来源于stack exchange,提问作者Anant Narayan
相关产品推荐
相关产品推荐

