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

后端 未结 8 1506
伪装坚强ぢ
伪装坚强ぢ 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:56

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

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

    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-measured to plumb something more prolific

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