简体   繁体   English

计算Node.js中的CPU使用率

[英]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. 我正在尝试计算运行我的nodejs应用程序的计算机上的CPU使用率,但是由于某种原因,输出比ubuntu上的系统监视器显示的输出高很多。 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%. 这输出〜89%,而系统监视器显示我所有的CPU都在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. os.cpu()提供的信息是自启动以来的平均用法。 To have information about the current usage of CPU, you could do something like this: 要了解有关CPU当前使用情况的信息,可以执行以下操作:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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