![](/img/trans.png)
[英]Measure the use of CPU of a Nodejs process from within the same Nodejs process
[英]Determine the CPU in use of a process nodejs
有没有一种方法可以获取正在执行子进程的CPU。 我有8个CPU。 因此,父代码启动了8个子进程。 这是节点代码:
// parent.js
var child_process = require('child_process');
var numchild = require('os').cpus().length;
var done = 0;
for (var i = 0; i < numchild; i++){
var child = child_process.fork('./child');
child.send((i + 1) * 1000);
child.on('message', function(message) {
console.log('[parent] received message from child:', message);
done++;
if (done === numchild) {
console.log('[parent] received all results');
}
});
}
// child.js
process.on('message', function(message) {
console.log('[child] received message from server:', message);
setTimeout(function() {
process.send({
child : process.pid,
result : message + 1
});
process.disconnect();
}, 10000);
});
通过child_process
no直接从child
对象派生。
但是,您可以使用其PID
- child.pid
并从节点执行例如UNIX ps -p <PID> -o psr
命令来解析其响应。 PSR
是在特定进程中使用的处理器的编号。
为此,您可以根据需要修改node.js shell命令执行中提出的解决方案:
function cmd_exec(cmd, args, cb_stdout, cb_end) {
var spawn = require('child_process').spawn,
child = spawn(cmd, args),
me = this;
me.exit = 0; // Send a cb to set 1 when cmd exits
child.stdout.on('data', function (data) { cb_stdout(me, data) });
child.stdout.on('end', function () { cb_end(me) });
}
foo = new cmd_exec('netstat', ['-rn'],
function (me, data) {me.stdout += data.toString();},
function (me) {me.exit = 1;}
);
function log_console() {
console.log(foo.stdout);
}
setTimeout(
// wait 0.25 seconds and print the output
log_console,
250);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.