electronCpuNormalization.ts 866 B

12345678910111213141516171819202122
  1. /**
  2. * Electron `percentCPUUsage` 的整机口径归一化。
  3. *
  4. * 资源管理器 UI 展示的整机 CPU 口径统一走这一份归一化实现:
  5. * darwin / win32 上 Chromium 已按整机归一化;linux 上是单核口径,需要除以逻辑核数。
  6. */
  7. import os from "node:os";
  8. export function normalizeElectronCpuToMachinePercent(
  9. cpu: number | null | undefined,
  10. options: { platform?: NodeJS.Platform; logicalCpuCount?: number } = {},
  11. ): number {
  12. const normalizedCpu = typeof cpu === "number" && Number.isFinite(cpu) ? cpu : 0;
  13. const platform = options.platform ?? process.platform;
  14. if (platform !== "linux") {
  15. return normalizedCpu;
  16. }
  17. const logicalCpuCount = options.logicalCpuCount ?? os.cpus().length;
  18. const scale = Number.isFinite(logicalCpuCount) && logicalCpuCount > 0 ? logicalCpuCount : 1;
  19. return normalizedCpu / scale;
  20. }