将 Node.js 中 os.cpus() 的输出转换为百分比

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9565912/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 15:16:53  来源:igfitidea点击:

Convert the output of os.cpus() in Node.js to percentage

node.jsoperating-systemcpu

提问by rogeriopvl

Is there a way to convert the os.cpus() info to percentage? Just like the output of iostat (on the CPU section).

有没有办法将 os.cpus() 信息转换为百分比?就像 iostat 的输出(在 CPU 部分)。

My code:

我的代码:

var os = require('os');
console.log(os.cpus());

The output:

输出:

[ { model: 'MacBookAir4,2',
    speed: 1800,
    times: 
     { user: 5264280,
       nice: 0,
       sys: 4001110,
       idle: 58703910,
       irq: 0 } },
  { model: 'MacBookAir4,2',
    speed: 1800,
    times: 
     { user: 2215030,
       nice: 0,
       sys: 1072600,
       idle: 64657440,
       irq: 0 } },
  { model: 'MacBookAir4,2',
    speed: 1800,
    times: 
     { user: 5973360,
       nice: 0,
       sys: 3197990,
       idle: 58773760,
       irq: 0 } },
  { model: 'MacBookAir4,2',
    speed: 1800,
    times: 
     { user: 2187650,
       nice: 0,
       sys: 1042550,
       idle: 64714820,
       irq: 0 } } ]

I would like to have the "times" metric converted to percentage, just like is show on the iostatcommand:

我想将“时间”指标转换为百分比,就像iostat命令中显示的一样:

  cpu
us sy id
6  3 91

I understand that the values in the nodejs function are in CPU ticks, but I have no idea what formula should I use to convert them to percentage :)

我知道 nodejs 函数中的值以 CPU 滴答为单位,但我不知道应该使用什么公式将它们转换为百分比:)

Thanks.

谢谢。

回答by Linus Gustav Larsson Thiel

According to the docs, timesis

根据文档times

an object containing the number of CPU ticks spent in: user, nice, sys, idle, and irq

一个包含 CPU 滴答数的对象:user、nice、sys、idle 和 irq

So you should just be able to sum the times and calculate the percentage, like below:

所以你应该能够总结时间并计算百分比,如下所示:

var cpus = os.cpus();

for(var i = 0, len = cpus.length; i < len; i++) {
    console.log("CPU %s:", i);
    var cpu = cpus[i], total = 0;

    for(var type in cpu.times) {
        total += cpu.times[type];
    }

    for(type in cpu.times) {
        console.log("\t", type, Math.round(100 * cpu.times[type] / total));
    }
}

EDIT:As Tom Frost says in the comments, this is the average usage since system boot. This is consistent with the question, since the same is true of iostat. However, iostathas the option of doing regular updates, showing the average usage since the last update. Tom's method would work well for implementing that.

编辑:正如 Tom Frost 在评论中所说,这是自系统启动以来的平均使用量。这与问题一致,因为iostat. 但是,iostat可以选择进行定期更新,显示自上次更新以来的平均使用情况。汤姆的方法可以很好地实现这一点。

回答by oscarm

This module, that caN be installed using NPM provides what you need:

这个可以使用 NPM 安装的模块提供了你需要的东西:

https://github.com/oscmejia/os-utils

https://github.com/oscmejia/os-utils

calle the cpuUsage(callback) method and you will get what you need.

调用 cpuUsage(callback) 方法,您将获得所需的内容。

回答by Arunoda Susiripala

If you are looking at the CPU Usage per process try node-usage

如果您正在查看每个进程的 CPU 使用率,请尝试使用 node-usage

回答by guybrush

a simple hack:

一个简单的黑客:

var os = require('os')
var samples = []
var prevCpus = os.cpus()

setInterval(sample,100)
setInterval(print,1000)

function print() {
  var result = {last10:null, last50:null, last100:null}
  var percent = 0
  var i = samples.length
  var j = 0
  while (i--) {
    j++
    if (samples[i].total > 0)
      percent += (100 - Math.round(100 * samples[i].idle / samples[i].total))
    if (j == 10)       result.last10  = percent/j   
    else if (j == 50)  result.last50  = percent/j    
    else if (j == 100) result.last100 = percent/j
  }
  console.log(result)
}

function sample() {
  currCpus = os.cpus()
  for (var i=0,len=currCpus.length;i<len;i++) {
    var prevCpu = prevCpus[i]
    var currCpu = currCpus[i]
    var deltas = {total:0}
    for (var t in prevCpu.times) 
      deltas.total += currCpu.times[t] - prevCpu.times[t]
    for (var t in prevCpu.times) 
      deltas[t] = currCpu.times[t] - prevCpu.times[t]
  }
  prevCpus = currCpus
  samples.push(deltas)
  if (samples.length>100) samples.shift()
}

you could use a metrics-lib like https://github.com/felixge/node-measuredto plumb something more prolific

你可以使用像https://github.com/felixge/node-measured这样的度量库来研究更多产的东西

回答by user3575777

This is my Solution

这是我的解决方案

Interval is in Seconds.

间隔以秒为单位。

10 will calculate load over the last 10 seconds!

10 将计算过去 10 秒内的负载!

var _  = require("underscore");
var os = require("os"); 
var interval = 1;
var old = _.map(os.cpus(),function(cpu){ return cpu.times;})

setInterval(function() {
    var result = [];
    var current = _.map(os.cpus(),function(cpu){ return cpu.times; })
    _.each(current, function(item,cpuKey){
        result[cpuKey]={}

        var oldVal = old[cpuKey];
        _.each(_.keys(item),function(timeKey){
            var diff = (  parseFloat((item[timeKey]) - parseFloat(oldVal[timeKey])) / parseFloat((interval*100)));
            var name = timeKey;
            if(timeKey == "idle"){
                name = "CPU"        
                diff = 100 - diff;
            }
            //console.log(timeKey + ":\t" + oldVal[timeKey] + "\t\t" + item[timeKey] + "\t\t" + diff);  
            result[cpuKey][name]=diff.toFixed(0);
        });
    });
    console.log(result);
    old=current;
}, (interval * 1000));

Outputs something like this on my 8-core every n-seconds

每 n 秒在我的 8 核上输出这样的内容

[ { user: '82', nice: '0', sys: '18', CPU: '100', irq: '0' },
  { user: '1', nice: '0', sys: '1', CPU: '3', irq: '0' },
  { user: '1', nice: '0', sys: '1', CPU: '3', irq: '0' },
  { user: '9', nice: '0', sys: '2', CPU: '11', irq: '0' },
  { user: '1', nice: '0', sys: '0', CPU: '1', irq: '0' },
  { user: '1', nice: '0', sys: '1', CPU: '2', irq: '0' },
  { user: '1', nice: '0', sys: '2', CPU: '2', irq: '0' },
  { user: '1', nice: '0', sys: '2', CPU: '3', irq: '0' } ]

Pushing this via socket.io into my Flow-Charts ;)

通过 socket.io 将其推送到我的流程图中;)

回答by tning

If you want to watch real time CPU and memory usage, you can try os-usage.

如果您想查看实时 CPU 和内存使用情况,可以尝试os-usage

The basic usage is like following:

基本用法如下:

var usage = require('os-usage');

// create an instance of CpuMonitor
var cpuMonitor = new usage.CpuMonitor();

// watch cpu usage overview
cpuMonitor.on('cpuUsage', function(data) {
    console.log(data);

    // { user: '9.33', sys: '56.0', idle: '34.66' }
});

You can also get processes that use most cpu resources:

您还可以获取使用最多 cpu 资源的进程:

cpuMonitor.on('topCpuProcs', function(data) {
    console.log(data);

    // [ { pid: '21749', cpu: '0.0', command: 'top' },
    //  { pid: '21748', cpu: '0.0', command: 'node' },
    //  { pid: '21747', cpu: '0.0', command: 'node' },
    //  { pid: '21710', cpu: '0.0', command: 'com.apple.iCloud' },
    //  { pid: '21670', cpu: '0.0', command: 'LookupViewServic' } ]
});

回答by math_lab3.ca

Here how I did it:

这是我是如何做到的:

var OS = require('os');
var oldCPUTime = 0
var oldCPUIdle = 0
function getLoad(){
    var cpus = OS.cpus()
    var totalTime = -oldCPUTime
    var totalIdle = -oldCPUIdle
    for(var i = 0; i < cpus.length; i++) {
        var cpu = cpus[i]
        for(var type in cpu.times) {
            totalTime += cpu.times[type];
            if(type == "idle"){
                totalIdle += cpu.times[type];
            }
        }
    }

    var CPUload = 100 - Math.round(totalIdle/totalTime*100))
    oldCPUTime = totalTime
    oldCPUIdle = totalIdle

    return {
        CPU:CPUload,
        mem:100 - Math.round(OS.freemem()/OS.totalmem()*100)
    }       
}

回答by lancha90

i'm using this code:

我正在使用此代码:

var cpu_used = function(){
var cpu = os.cpus();

var counter = 0;
var total=0;

var free=0;
var sys=0;
var user=0;

for (var i = 0; i<cpu.length ; i++) {

    counter++;
    total=parseFloat(cpu[i].times.idle)+parseFloat(cpu[i].times.sys)+parseFloat(cpu[i].times.user)+parseFloat(cpu[i].times.irq)+parseFloat(cpu[i].times.nice);

    free+=100*(parseFloat(cpu[i].times.idle)/total);
    sys+=100*(parseFloat(cpu[i].times.sys)/total);
    user+=100*(parseFloat(cpu[i].times.user)/total);
};

console.log('CPU %s : %s + %s + %s',i,(free/counter),(user/counter),(sys/counter));

}