节点集群工作者memoryUsage

时间:2015-07-01 17:52:09

标签: node.js macos unix cluster-computing worker

有没有人知道是否有一种独立于平台的方式来获取工作者的内存使用情况? 我希望它能像这样工作:

console.log('App process memoryUsage: ',process.memoryUsage());
cluster.on('online',function(worker){    // doesn't work! 
  console.log('Workers memory usage: ',worker.process.memoryUsage());  
});

但工人流程没有方法memoryUsage()

这是否有正当理由?

实现这一目标的唯一想法是在linux上使用unix top -pid 1234(macosx)或top -p 1234。并按process.plattform切换。

1 个答案:

答案 0 :(得分:3)

是的,您确实无法从工作人员的流程属性中获取memoryUsage。我不确定为什么它没有实现,但你可以通过这种方法实现同样的目标:

var cluster = require('cluster');
var numCPUs = require('os').cpus().length;
if (cluster.isMaster) {
  for (var i = 0; i < numCPUs; i++) {
    cluster.fork();
  }
  cluster.on('exit', function(worker, code, signal) {
    console.log('worker ' + worker.process.pid + ' died');
  });
  cluster.on('online', function(worker, code, signal) {
    worker.send('memoryUsage');
    worker.on('message', function(dd) {
      if (dd.event == 'memoryUsage') {
        console.log("Worker with ID: %d consumes %imb of memory", worker.id, dd.data.heapTotal / 1024 / 1024);
      }
    });
  });
  console.log("Master consumes %imb of memory", process.memoryUsage().heapTotal / 1024 / 1024);
} else {
  if (cluster.worker.id == 1) {
    a = [];
    for (var i = 0; i < 1000000; i++) {
      //just to see the difference in memory usage.
      a.push(Number.MAX_SAFE_INTEGER);
    };
  }
  process.on('message', function(msg) {
    if (msg == 'memoryUsage') {
      process.send({
        event: msg,
        data: process.memoryUsage()
      });
    }
  });
}

8核系统的输出:

user$ node ClusterTest.js 
Master consumes 6mb of memory
Worker with ID: 2 consumes 5mb of memory
Worker with ID: 6 consumes 5mb of memory
Worker with ID: 3 consumes 5mb of memory
Worker with ID: 4 consumes 5mb of memory
Worker with ID: 7 consumes 5mb of memory
Worker with ID: 5 consumes 5mb of memory
Worker with ID: 8 consumes 5mb of memory
Worker with ID: 1 consumes 39mb of memory
^C
user$