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

后端 未结 8 1491
伪装坚强ぢ
伪装坚强ぢ 2020-12-08 11:27

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

My code:

var os = require(\'os\');
c         


        
相关标签:
8条回答
  • 2020-12-08 11:36

    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));
    
    }
    
    0 讨论(0)
  • 2020-12-08 11:37

    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)
        }       
    }
    
    0 讨论(0)
  • 2020-12-08 11:38

    If you want to watch real time CPU and memory usage, you can try 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:

    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' } ]
    });
    
    0 讨论(0)
  • 2020-12-08 11:40

    This is my Solution

    Interval is in Seconds.

    10 will calculate load over the last 10 seconds!

    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

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

    0 讨论(0)
  • 2020-12-08 11:48

    According to the docs, times is

    an object containing the number of CPU ticks spent in: user, nice, sys, idle, and 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, iostat has the option of doing regular updates, showing the average usage since the last update. Tom's method would work well for implementing that.

    0 讨论(0)
  • 2020-12-08 11:51

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

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

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

    0 讨论(0)
提交回复
热议问题