简体   繁体   中英

calculating cpu usage in nodejs

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?

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM