UNPKG

@naturalcycles/nodejs-lib

Version:
87 lines (86 loc) 2.89 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.processSharedUtil = exports.memoryUsageFull = exports.memoryUsage = void 0; const os = require("os"); const js_lib_1 = require("@naturalcycles/js-lib"); /* eslint-disable @typescript-eslint/explicit-module-boundary-types */ function memoryUsage() { const { rss, external, heapUsed, heapTotal } = process.memoryUsage(); return { rss: (0, js_lib_1._mb)(rss), heapTotal: (0, js_lib_1._mb)(heapTotal), heapUsed: (0, js_lib_1._mb)(heapUsed), external: (0, js_lib_1._mb)(external), }; } exports.memoryUsage = memoryUsage; function memoryUsageFull() { const { rss, external, heapUsed, heapTotal } = process.memoryUsage(); const totalMem = os.totalmem(); const freeMem = os.freemem(); return { rss: (0, js_lib_1._mb)(rss), heapTotal: (0, js_lib_1._mb)(heapTotal), heapUsed: (0, js_lib_1._mb)(heapUsed), external: (0, js_lib_1._mb)(external), totalMem: (0, js_lib_1._mb)(totalMem), freeMem: (0, js_lib_1._mb)(freeMem), usedMem: (0, js_lib_1._mb)(totalMem - freeMem), }; } exports.memoryUsageFull = memoryUsageFull; class ProcessUtil { startMemoryTimer(intervalMillis = 1000) { console.log(memoryUsage()); this.timer = setInterval(() => { console.log(memoryUsage()); }, intervalMillis); } stopMemoryTimer(afterMillis = 0) { setTimeout(() => clearInterval(this.timer), afterMillis); } cpuAvg() { const avg = os.loadavg(); return { avg1: avg[0].toFixed(2), avg5: avg[1].toFixed(2), avg15: avg[2].toFixed(2), }; } cpuInfo() { const c = os.cpus()[0]; return { count: os.cpus().length, model: c.model, speed: c.speed, }; } async cpuPercent(ms) { const stats1 = this.getCPUInfo(); const startIdle = stats1.idle; const startTotal = stats1.total; return new Promise(resolve => { setTimeout(() => { const stats2 = this.getCPUInfo(); const endIdle = stats2.idle; const endTotal = stats2.total; const idle = endIdle - startIdle; const total = endTotal - startTotal; const perc = idle / total; resolve(Math.round((1 - perc) * 100)); }, ms); }); } getCPUInfo() { // eslint-disable-next-line unicorn/no-array-reduce return os.cpus().reduce((r, cpu) => { r['idle'] += cpu.times.idle; Object.values(cpu.times).forEach(m => (r['total'] += m)); return r; }, { idle: 0, total: 0, }); } } exports.processSharedUtil = new ProcessUtil();