码桶

发现社区成员的开源项目

奶狗 /

ng-webot

公开
main
ng-webot/lib/sys-stats.js
sys-stats.js1.5 KB
// 系统资源统计:后台定时采样进程 CPU、系统 CPU、内存、运行时间。
// 统计接口读取最新采样值,避免每次请求阻塞测量。
const os = require('os');

const START_TIME = Date.now();
let lastCpu = process.cpuUsage();
let lastTs = Date.now();
let procCpu = 0; // 进程 CPU 占用(%)
let sysCpu = 0;  // 系统整体 CPU 占用(%)

function sample() {
  const cur = process.cpuUsage();
  const now = Date.now();
  const totalMicro = (cur.user - lastCpu.user) + (cur.system - lastCpu.system);
  const elapsedMicro = (now - lastTs) * 1000;
  procCpu = elapsedMicro > 0 ? (totalMicro / elapsedMicro) * 100 : 0;
  lastCpu = cur;
  lastTs = now;

  const cpus = os.cpus();
  let idle = 0;
  let total = 0;
  for (const c of cpus) {
    for (const k in c.times) total += c.times[k];
    idle += c.times.idle;
  }
  sysCpu = total > 0 ? (1 - idle / total) * 100 : 0;
}

sample();
const timer = setInterval(sample, 1000);
if (timer.unref) timer.unref();

function gb(v) {
  return Math.round((v / 1073741824) * 10) / 10;
}

function getSysStats() {
  const mem = process.memoryUsage();
  return {
    cpu: Math.round(procCpu * 10) / 10,
    systemCpu: Math.round(sysCpu * 10) / 10,
    processMemoryMB: Math.round(mem.rss / 1048576),
    systemMemoryTotalGB: gb(os.totalmem()),
    systemMemoryFreeGB: gb(os.freemem()),
    uptimeSec: Math.floor((Date.now() - START_TIME) / 1000),
    startedAt: Math.floor(START_TIME / 1000),
  };
}

module.exports = { getSysStats };