监视Node.js进程中的最大内存消耗

我正在寻找一种跨平台的方式来可靠地监控Node.js进程中的最大内存消耗,无论是否存在泄漏。

在我的情况下的过程都是真正的应用程序和综合testing。

我会期待它的工作

process.on('exit', () => { console.log('Max memory consumption: ' + ...); }); 

有可能追踪内存消耗与node --trace_gc ... ,但这导致了难以阅读的输出(可能很难分析编程)。 另外,即使内存使用量很大,当脚本结束得太快,GC也不会发生。

从我所看到的主题memwatch ,通常build议使用memwatch ,比如:

 require('memwatch-next').on('stats', stats => { console.log('Max memory consumption: ' + stats.max); }); 

但在我的情况下,只有当GC已经发生或根本没有触发时才触发,因此确定RAM消耗峰值是没有用的。

如果可能,我宁愿避免像node-inspector器那样的GUI工具。

这个最大的内存消耗是否可以从应用程序本身或CLI单独进行可靠地检索,跨平台?

您可以使用Node.js process.memoryUsage()方法来获取内存使用情况stat:

process.memoryUsage()方法返回一个描述Node.js进程的内存使用情况的对象,以字节为单位。

它返回以下格式的对象:

 { rss: 4935680, // Resident Set Size heapTotal: 1826816, // Total Size of the Heap heapUsed: 650472, // Heap actually Used external: 49879 // memory usage of C++ objects bound to JavaScript objects managed by V8 } 

为了在Node.js进程中获得最大的内存消耗,可以使用process.nextTick方法。 process.nextTick()方法将callback添加到下一个打勾队列 。 一旦事件循环的当前轮到运行完成,当前在下一个滴答队列中的所有callback将被调用。

 let _maxMemoryConsumption; let _dtOfMaxMemoryConsumption; process.nextTick(() => { let memUsage = process.memoryUsage(); if (memUsage.rss > _maxMemoryConsumption) { _maxMemoryConsumption = memUsage.rss; _dtOfMaxMemoryConsumption = new Date(); } }); process.on('exit', () => { console.log(`Max memory consumption: ${_maxMemoryConsumption} at ${_dtOfMaxMemoryConsumption}`); }); 

如果您尝试从自身内部对进程进行基准testing,则会导致内存使用率值变形。 (如果你想了解更多的信息,只需评论)


这是一个用于检查另一个进程的内存使用情况的小程序( crossplatform ),它产生一个独立的进程,每100ms查看一次内存的使用情况,以便find最高的峰值,每次输出一个新的峰值,一旦孩子停止结束了。

它使用pidusage这是一个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] 

这个工具可以防止你添加膨胀到你真正想要进行基准testing的进程的代码,所以这样你就不会得到不同的内存使用值,因为你的膨胀/基准testing代码也会增加内存的使用。