loadmill-monitor
Version:
Performance monitoring for Node.js
82 lines (61 loc) • 1.67 kB
JavaScript
class Sampler {
constructor (sampleDelay, maxSamples) {
this.samples = [];
this.sampleDelay = sampleDelay || 1000;
this.maxSamples = maxSamples || 10000;
}
sampleUntil(stopTime, onSample) {
const now = Date.now();
if (stopTime <= now) {
this.stopSampling();
return;
}
this.stopTime = stopTime;
this.onSample = onSample;
if (!this.sampleTimer) {
this.lastPopTime = now;
this.previousSampleTime = now;
this.previousCpuUsage = process.cpuUsage();
this.sampleTimer = setInterval(this._recordSample.bind(this), this.sampleDelay);
this.sampleTimer.unref();
}
}
popSamples() {
this.lastPopTime = Date.now();
const samples = this.samples;
this.samples = [];
return samples;
}
stopSampling() {
if (this.sampleTimer) {
clearInterval(this.sampleTimer);
this.sampleTimer = null;
this.samples = [];
}
}
_recordSample() {
const timestamp = Date.now();
if (timestamp >= this.stopTime) {
this.stopSampling();
return;
}
const duration = timestamp - this.previousSampleTime;
this.previousSampleTime = timestamp;
const cpuUsage = process.cpuUsage(this.previousCpuUsage);
this.previousCpuUsage = process.cpuUsage();
const memoryUsage = process.memoryUsage();
this.samples.push({
duration,
timestamp,
cpuUsage,
memoryUsage,
});
if (this.samples.length >= this.maxSamples) {
this.samples = this.samples.slice(Math.floor(this.samples.length / 2));
}
if (this.onSample) {
this.onSample();
}
}
}
module.exports = Sampler;