fix: High CPU due to WMI queries (#5924)

* fix: High CPU due to WMI queries
This commit is contained in:
naman-bruno
2025-10-30 15:32:21 +05:30
committed by GitHub
parent 73caaef42b
commit b69db7b44b
7 changed files with 328 additions and 127 deletions

View File

@@ -1,4 +1,4 @@
const pidusage = require('pidusage');
const { app } = require('electron');
class SystemMonitor {
constructor() {
@@ -19,38 +19,59 @@ class SystemMonitor {
this.emitSystemStats(win);
// Set up periodic monitoring
this.intervalId = setInterval(() => {
// Use setTimeout pattern instead of setInterval to avoid overlapping calls
this.scheduleNextEmit(win, intervalMs);
}
scheduleNextEmit(win, intervalMs) {
if (!this.isMonitoring) {
return;
}
this.intervalId = setTimeout(() => {
this.emitSystemStats(win);
this.scheduleNextEmit(win, intervalMs);
}, intervalMs);
}
stop() {
if (this.intervalId) {
clearInterval(this.intervalId);
clearTimeout(this.intervalId);
this.intervalId = null;
}
this.isMonitoring = false;
}
async emitSystemStats(win) {
emitSystemStats(win) {
try {
const pid = process.pid;
const stats = await pidusage(pid);
const uptime = (Date.now() - this.startTime) / 1000;
const metrics = app.getAppMetrics();
const currentTime = Date.now();
let totalCPU = 0;
let totalMemory = 0;
for (const metric of metrics) {
totalCPU += metric.cpu.percentCPUUsage;
totalMemory += metric.memory.workingSetSize;
}
const uptime = (currentTime - this.startTime) / 1000;
const systemResources = {
cpu: stats.cpu || 0,
memory: stats.memory || 0,
pid: pid,
cpu: totalCPU,
memory: totalMemory,
pid: process.pid,
uptime: uptime,
timestamp: new Date().toISOString()
};
win.webContents.send('main:filesync-system-resources', systemResources);
if (win && !win.isDestroyed()) {
win.webContents.send('main:filesync-system-resources', systemResources);
}
} catch (error) {
console.error('Error getting system stats:', error);
// Fallback stats if pidusage fails
// Fallback stats using process.memoryUsage()
const fallbackStats = {
cpu: 0,
memory: process.memoryUsage().rss,
@@ -59,7 +80,9 @@ class SystemMonitor {
timestamp: new Date().toISOString()
};
win.webContents.send('main:filesync-system-resources', fallbackStats);
if (win && !win.isDestroyed()) {
win.webContents.send('main:filesync-system-resources', fallbackStats);
}
}
}