UNPKG

2.41 kBPlain TextView Raw
1import { _mb } from '@naturalcycles/js-lib'
2import * as os from 'os'
3
4/* eslint-disable @typescript-eslint/explicit-module-boundary-types */
5
6export function memoryUsage() {
7 const { rss, external, heapUsed, heapTotal } = process.memoryUsage()
8 return {
9 rss: _mb(rss),
10 heapTotal: _mb(heapTotal),
11 heapUsed: _mb(heapUsed),
12 external: _mb(external),
13 }
14}
15
16export function memoryUsageFull() {
17 const { rss, external, heapUsed, heapTotal } = process.memoryUsage()
18 const totalMem = os.totalmem()
19 const freeMem = os.freemem()
20 return {
21 rss: _mb(rss),
22 heapTotal: _mb(heapTotal),
23 heapUsed: _mb(heapUsed),
24 external: _mb(external),
25 totalMem: _mb(totalMem),
26 freeMem: _mb(freeMem),
27 usedMem: _mb(totalMem - freeMem),
28 }
29}
30
31class ProcessUtil {
32 private timer!: NodeJS.Timer
33
34 startMemoryTimer(intervalMillis = 1000): void {
35 console.log(memoryUsage())
36
37 this.timer = setInterval(() => {
38 console.log(memoryUsage())
39 }, intervalMillis)
40 }
41
42 stopMemoryTimer(afterMillis = 0): void {
43 setTimeout(() => clearInterval(this.timer), afterMillis)
44 }
45
46 cpuAvg(): { avg1: string; avg5: string; avg15: string } {
47 const avg = os.loadavg()
48 return {
49 avg1: avg[0]!.toFixed(2),
50 avg5: avg[1]!.toFixed(2),
51 avg15: avg[2]!.toFixed(2),
52 }
53 }
54
55 cpuInfo(): { count: number; model: string; speed: number } {
56 const c = os.cpus()[0]!
57 return {
58 count: os.cpus().length,
59 model: c.model,
60 speed: c.speed,
61 }
62 }
63
64 async cpuPercent(ms: number): Promise<number> {
65 const stats1 = this.getCPUInfo()
66 const startIdle = stats1.idle
67 const startTotal = stats1.total
68
69 return new Promise<number>(resolve => {
70 setTimeout(() => {
71 const stats2 = this.getCPUInfo()
72 const endIdle = stats2.idle
73 const endTotal = stats2.total
74
75 const idle = endIdle - startIdle
76 const total = endTotal - startTotal
77 const perc = idle / total
78
79 resolve(Math.round((1 - perc) * 100))
80 }, ms)
81 })
82 }
83
84 private getCPUInfo() {
85 // eslint-disable-next-line unicorn/no-array-reduce
86 return os.cpus().reduce(
87 (r, cpu) => {
88 r['idle'] += cpu.times.idle
89 Object.values(cpu.times).forEach(m => (r['total'] += m))
90 return r
91 },
92 {
93 idle: 0,
94 total: 0,
95 },
96 )
97 }
98}
99
100export const processSharedUtil = new ProcessUtil()