this.broker.Promise.resolve() .then(() => cpuUsage().then(res => { this.set(METRIC.OS_CPU_UTILIZATION, res.avg); try { const cpus = os.cpus(); this.set(METRIC.OS_CPU_TOTAL, cpus.length); this.set(METRIC.OS_CPU_USER, cpus.reduce((a,b) => a + b.times.user, 0)); this.set(METRIC.OS_CPU_SYSTEM, cpus.reduce((a,b) => a + b.times.sys, 0)); cpus.forEach((cpu, index) => { this.set(METRIC.OS_CPU_INFO_MODEL, cpu.model, { index }); this.set(METRIC.OS_CPU_INFO_SPEED, cpu.speed, { index }); this.set(METRIC.OS_CPU_INFO_TIMES_USER, cpu.times.user, { index }); this.set(METRIC.OS_CPU_INFO_TIMES_SYS, cpu.times.sys, { index }); }); } catch(err) { // silent } })) .catch(() => { // silent this.logger.warn("Unable to collect CPU usage metrics.", err); }) .then(() => { this.logger.debug(`Collected common metric values in ${duration.toFixed(3)} msec.`); })
os.cpus().map(cpu => cpu.times)
os .cpus() .map(function(cpu) { return cpu.model }) .reduce(function(o, model) { if (!o[model]) o[model] = 0 o[model]++ return o }, {})
os.cpus().filter(function(cpu, index) { const hasHyperthreading = cpu.model.includes("Intel"); const isOdd = index % 2 === 1; return !hasHyperthreading || isOdd; })
function cpuAverage () { const times = { user: 0, nice: 0, sys: 0, idle: 0, irq: 0, total: 0 } const cpus = os.cpus() for (const cpu of cpus) { for (const type of Object.keys(cpu.times)) { times[type] += cpu.times[type] times.total += cpu.times[type] } } // Average over CPU count const averages = {} for (const type of Object.keys(times)) { averages[type] = times[type] / cpus.length } return averages }
cpus.reduce((total, cpu) => total + cpu.times.idle, 0)
//Create function to get CPU information function cpuAverage() { //Initialise sum of idle and time of cores and fetch CPU info var totalIdle = 0, totalTick = 0; var cpus = os.cpus(); //Loop through CPU cores for(var i = 0, len = cpus.length; i < len; i++) { //Select CPU core var cpu = cpus[i]; //Total up the time in the cores tick for(type in cpu.times) { totalTick += cpu.times[type]; } //Total up the idle time of the core totalIdle += cpu.times.idle; } //Return the average Idle and Tick times return {idle: totalIdle / cpus.length, total: totalTick / cpus.length}; }
os.cpus().map(function (cpu) { delete cpu.times return cpu })