fix(cpu): Resolved boundary condition issues when calculating CPU utilization (#988)

Added checks for coreIdx out-of-bounds and totalDelta being zero to prevent array out-of-bounds and division-by-zero errors
This commit is contained in:
GT610
2026-01-06 12:48:13 +08:00
committed by GitHub
parent 78ef181d4a
commit 7c35abe30e

View File

@@ -33,9 +33,11 @@ class Cpus extends TimeSeq<SingleCpuCore> {
double usedPercent({int coreIdx = 0}) {
if (now.length != pre.length) return 0;
if (now.isEmpty) return 0;
if (coreIdx >= now.length) return 0;
try {
final idleDelta = now[coreIdx].idle - pre[coreIdx].idle;
final totalDelta = now[coreIdx].total - pre[coreIdx].total;
if (totalDelta == 0) return 0;
final used = idleDelta / totalDelta;
return used.isNaN ? 0 : 100 - used * 100;
} catch (e, s) {