1 | 'use strict'
|
2 |
|
3 | function hrtime2ms (time) {
|
4 | return time[0] * 1e3 + time[1] * 1e-6
|
5 | }
|
6 |
|
7 | class ProcessStat {
|
8 | constructor (sampleInterval) {
|
9 | if (typeof sampleInterval !== 'number') {
|
10 | throw new TypeError('sample interval must be a number')
|
11 | }
|
12 |
|
13 | this.sampleInterval = sampleInterval
|
14 | this.refresh()
|
15 | }
|
16 |
|
17 | _sampleDelay (elapsedTime) {
|
18 |
|
19 | return Math.max(0, elapsedTime - this.sampleInterval)
|
20 | }
|
21 |
|
22 | _sampleCpuUsage (elapsedTime) {
|
23 | const elapsedCpuUsage = process.cpuUsage(this._lastSampleCpuUsage)
|
24 |
|
25 | const elapsedCpuUsageTotal = (
|
26 | elapsedCpuUsage.user + elapsedCpuUsage.system
|
27 | ) / 1000
|
28 |
|
29 | return elapsedCpuUsageTotal / elapsedTime
|
30 | }
|
31 |
|
32 | refresh () {
|
33 | this._lastSampleTime = process.hrtime()
|
34 | this._lastSampleCpuUsage = process.cpuUsage()
|
35 | }
|
36 |
|
37 | sample () {
|
38 | const elapsedTime = hrtime2ms(process.hrtime(this._lastSampleTime))
|
39 |
|
40 | return {
|
41 | timestamp: Date.now(),
|
42 | delay: this._sampleDelay(elapsedTime),
|
43 | cpu: this._sampleCpuUsage(elapsedTime),
|
44 | memory: process.memoryUsage(),
|
45 | handles: process._getActiveHandles().length
|
46 | }
|
47 | }
|
48 | }
|
49 |
|
50 | module.exports = ProcessStat
|