Code coverage report for cpu/index.js

Statements: 100% (25 / 25)      Branches: 100% (4 / 4)      Functions: 100% (8 / 8)      Lines: 100% (25 / 25)      Ignored: none     

All files » cpu/ » index.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 542   2 4 4 20         2 3 1     2 1 1     2 2   2 2 2     2 10     2 2 10     2 2   2                   2      
var os = require('os')
 
var withEvery = function(callback) {
  os.cpus().forEach(function(cpu, index) {
    Object.keys(cpu.times).forEach(function(key) {
      callback(index, key, cpu.times[key])
    })
  })
}
 
module.exports = function(timeout, callback) {
  if(arguments.length == 0) {
    throw new Error('Please pass a callback to cpu-stats')
  }
 
  if(arguments.length == 1) {
    callback = timeout
    timeout = 1000
  }
 
  var initial = []
  var values = []
 
  for(var i = 0; i < os.cpus().length; i++) {
    initial.push({})
    values.push({})
  }
 
  withEvery(function(index, key, value) {
    initial[index][key] = value
  })
 
  setTimeout(function() {
    withEvery(function(index, key, value) {
      values[index][key] = value - initial[index][key]
    })
 
    var output = values.map(function(value) {
      var total = value.user + value.nice + value.sys + value.idle + value.irq
 
      return {
        cpu: ((total - value.idle) / total) * 100,
        user: (value.user / total) * 100,
        nice: (value.nice / total) * 100,
        sys: (value.sys / total) * 100,
        idle: (value.idle / total) * 100,
        irq: (value.irq / total) * 100
      }
    })
 
    callback(undefined, output)
  }, timeout)
}