import hilog from '@ohos.hilog'; import file from '@ohos.file.fs' export class CpuUsageMonitor { private static readonly TAG: string = 'CpuUsageMonitor'; // 读取/proc/stat文件的第一行,获取CPU的总时间信息 private static getCpuUsage(): number[] { let cpuTimes: number[] = []; try { let result = file.openSync('/proc/stat', file.OpenMode.READ_ONLY); let buffer = new ArrayBuffer(1024); let len = file.readSync(result.fd, buffer, { offset: 0 }); let content = String.fromCharCode.apply(null, new Uint8Array(buffer, 0, len)); file.closeSync(result.fd); let lines = content.split('\n'); if (lines.length > 0 && lines[0].startsWith('cpu ')) { let parts = lines[0].split(/\s+/); for (let i = 1; i <= 7; i++) { cpuTimes.push(parseInt(parts[i])); } } } catch (err) { hilog.error(0x0000, this.TAG, `Failed to read /proc/stat: ${err.message}`); } return cpuTimes; } // 计算CPU使用率 private static calculateCpuUsage(prevCpuTimes: number[], currCpuTimes: number[]): number { let prevIdle = prevCpuTimes[3] + prevCpuTimes[4]; // idle + iowait let currIdle = currCpuTimes[3] + currCpuTimes[4]; // idle + iowait let prevTotal = prevCpuTimes.reduce((a, b) => a + b, 0); let currTotal = currCpuTimes.reduce((a, b) => a + b, 0); let totalDiff = currTotal - prevTotal; let idleDiff = currIdle - prevIdle; if (totalDiff === 0) { return 0; } return 100 * (totalDiff - idleDiff) / totalDiff; } public static printCpuUsage(): void { setInterval(() => { let prevCpuTimes = this.getCpuUsage(); setTimeout(() => { let currCpuTimes = this.getCpuUsage(); let cpuUsage = this.calculateCpuUsage(prevCpuTimes, currCpuTimes); hilog.info(0x0000, this.TAG, `Current CPU Usage: ${cpuUsage.toFixed(2)}%`); }, 1000); // 等待1秒 }, 5000) } }