Skip to content

Commit

Permalink
Implementing CPU usage calculation
Browse files Browse the repository at this point in the history
  • Loading branch information
r3na authored Jul 9, 2020
1 parent 0e5b71a commit d0ef1b6
Showing 1 changed file with 34 additions and 1 deletion.
35 changes: 34 additions & 1 deletion stats.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,36 @@
'use strict'

var os = require('os')

var startMeasure = cpuAverage()

function cpuAverage () {
var totalIdle = 0
var totalTick = 0
var cpus = os.cpus()
for (var i = 0, len = cpus.length; i < len; i++) {
var cpu = cpus[i]
for (var type in cpu.times) {
totalTick += cpu.times[type]
}
totalIdle += cpu.times.idle
}
return {
idle: totalIdle / cpus.length,
total: totalTick / cpus.length
}
}

var cpuUsageInterval = setInterval(cpuCalculation, 1000)

function cpuCalculation () {
var endMeasure = cpuAverage()
var idleDifference = endMeasure.idle - startMeasure.idle
var totalDifference = endMeasure.total - startMeasure.total
var cpuPercentage = 100 - ~~(100 * idleDifference / totalDifference)
this.stats.cpuUsage = cpuPercentage
}

function client () {
this.stats.connectedClients++
if (this.stats.connectedClients > this.stats.maxConnectedClients) {
Expand Down Expand Up @@ -35,7 +66,8 @@ function wire (aedesInstance, options) {
connectedClients: 0,
publishedMessages: 0,
started: new Date(),
time: new Date()
time: new Date(),
cpuUsage: 0,
}

function doPub (topic, value) {
Expand All @@ -61,6 +93,7 @@ function wire (aedesInstance, options) {
doPub('messages/publish/sent', stats.publishedMessages)
doPub('memory/heap/current', mem.heapUsed)
doPub('memory/heap/maximum', mem.heapTotal)
doPub('cpu/usage', stats.cpuUsage)
}

aedesEvents.forEach(function (event) {
Expand Down

0 comments on commit d0ef1b6

Please sign in to comment.