如果您尝试从进程内部对进程进行基准测试,您的内存使用值将会失真。 (如果您想了解更多信息,请发表评论)
这是我编写的一个小(跨平台)工具,用于检查另一个进程的内存使用情况,它生成一个独立进程并每 100 毫秒监视一次内存使用情况,以便找到最高峰,输出每次发现一个新的高峰,一旦孩子结束就停止。
它使用pidusage,这是一个跨平台进程(cpu % 和)内存 PID 的使用
允许自定义 spawn(参数与 spawn 一起传递)[可以为命令行使用而更新]
它也适用于任何节点二进制名称,因为它将重用用于启动此工具的名称。
'use strict'
const UI = {}; var ñ = " "
const pusage = require('pidusage');
//:Setup the 'cmd' array to be the file and arguments to be used
const ANALYSIS = {cmd:['child.js']}
ANALYSIS.child = require('child_process').spawn(
process.argv[0], // reuse to work with the same binary name used to run this (node|nodejs|...)
ANALYSIS.cmd, // array with filePath & arguments to spawn for this analisis
{ //So the child_process doesn't behave like a child
detached:true,
stdio:['ignore'],
env:null
}
);
//:The Analysis
DoAnalysis(ANALYSIS.child.pid);
ANALYSIS.child.unref()
var memPeak = 0;
function PIDStat(){
pusage.stat(ANALYSIS.pid, function(err, stat) {
if(err){ CheckError(err) }else{
if(stat.memory > memPeak){memPeak=stat.memory;PrintStat()}
setTimeout(PIDStat,100); pusage.unmonitor(process.pid)
}
})
}
//:UI (just for display)
function DoAnalysis(PID){
var s = '═'.repeat(ANALYSIS.cmd[0].toString().length)
ANALYSIS.pid = PID;
UI.top = '╒═'+s+'═╕'
UI.mid = '│ '+ANALYSIS.cmd[0]+' │'
UI.bot = '╘═'+s+'═╛'
console.log(UI.x);
PIDStat()
}
function PrintStat(){
console.clear()
console.log('\n',UI.top,'\n',UI.mid,'PEAK MEM. :',memPeak,'\n',UI.bot)
}
function CheckError(e){
switch(e.code){
case "ENOENT": console.log(" [the analysis ended]\n"); break;
default: console.log("[/!\\ error]\n",e); break
}
}
将产生以下输出:
╒══════════╕
│ child.js │ PEAK MEM. : 28737536
╘══════════╛
[the analysis ended]
此工具可防止您将膨胀添加到您实际想要进行基准测试的进程的代码中,因此您不会获得不同的内存使用值,因为您的膨胀/基准测试代码也会向该进程添加内存使用。