1

I'm trying to calculate the CPU usage on the computer running my nodejs app but for some reason the output is a lot higher than what my system monitor on ubuntu is showing me. Here is my code:

const cores = _.map(os.cpus(), 'times')
const free = _.sumBy(cores, 'idle')
const total = _.sumBy(cores, c => _.sum(_.values(c)))
const usage = free * 100 / total
console.log(usage)

This outputs ~89% whereas the system monitor shows that all of my CPUs are under 30%. I also tried calcualting it on just one core like this:

console.log(cores[1].idle / _.sum(_.values(cores[1])))

But this still showed a similar number that was way too high. Am I doing something wrong?

ninesalt
  • 4,054
  • 5
  • 35
  • 75

1 Answers1

0

I think you should check out the answer to this question.

The information provided by os.cpu() is an average usage since startup. To have information about the current usage of CPU, you could do something like this:

let cores = _.map(os.cpus(), 'times');
let freeBefore = _.sumBy(cores, 'idle');
let totalBefore = _.sumBy(cores, c => _.sum(_.values(c)));

setTimeout(() => {
  let cores = _.map(os.cpus(), 'times');
  let free = _.sumBy(cores, 'idle') - freeBefore;
  let total = _.sumBy(cores, c => _.sum(_.values(c))) - totalBefore;

  let usage = free * 100 / total;
  console.log(usage);
}, 500);
oniramarf
  • 843
  • 1
  • 11
  • 27