UNPKG

1.21 kBJavaScriptView Raw
1'use strict'
2
3function hrtime2ms (time) {
4 return time[0] * 1e3 + time[1] * 1e-6
5}
6
7class 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 // delay can't be negative, so truncate to 0
19 return Math.max(0, elapsedTime - this.sampleInterval)
20 }
21
22 _sampleCpuUsage (elapsedTime) {
23 const elapsedCpuUsage = process.cpuUsage(this._lastSampleCpuUsage)
24 // convert to from µs to ms
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
50module.exports = ProcessStat