我该如何监控Node.js的内存使用情况?
内置的process模块有一个方法memoryUsage
,可以提供当前 Node.js 进程的内存使用情况。以下是在 Node v0.12.2 上 64 位系统中的示例:
$ node --expose-gc
> process.memoryUsage(); // Initial usage
{ rss: 19853312, heapTotal: 9751808, heapUsed: 4535648 }
> gc(); // Force a GC for the baseline.
undefined
> process.memoryUsage(); // Baseline memory usage.
{ rss: 22269952, heapTotal: 11803648, heapUsed: 4530208 }
> var a = new Array(1e7); // Allocate memory for 10m items in an array
undefined
> process.memoryUsage(); // Memory after allocating so many items
{ rss: 102535168, heapTotal: 91823104, heapUsed: 85246576 }
> a = null; // Allow the array to be garbage-collected
null
> gc(); // Force GC (requires node --expose-gc)
undefined
> process.memoryUsage(); // Memory usage after GC
{ rss: 23293952, heapTotal: 11803648, heapUsed: 4528072 }
> process.memoryUsage(); // Memory usage after idling
{ rss: 23293952, heapTotal: 11803648, heapUsed: 4753376 }
在这个简单的例子中,你可以看到分配一个包含1000万个元素的数组大约会消耗80MB的内存(查看heapUsed
)。
如果你查看V8的源代码(Array::New
, Heap::AllocateRawFixedArray
, FixedArray::SizeFor
),那么你会看到一个数组使用的内存是一个固定值,再加上长度乘以指针的大小。后者在64位系统上为8个字节,这说明观察到的内存差异为8 x 10 = 80MB是有道理的。
您可以使用 node.js process.memoryUsage()
方法:
const formatMemoryUsage = (data) => `${Math.round(data / 1024 / 1024 * 100) / 100} MB`;
const memoryData = process.memoryUsage();
const memoryUsage = {
rss: `${formatMemoryUsage(memoryData.rss)} -> Resident Set Size - total memory allocated for the process execution`,
heapTotal: `${formatMemoryUsage(memoryData.heapTotal)} -> total size of the allocated heap`,
heapUsed: `${formatMemoryUsage(memoryData.heapUsed)} -> actual memory used during the execution`,
external: `${formatMemoryUsage(memoryData.external)} -> V8 external memory`,
};
console.log(memoryUsage);
/*
{
"rss": "177.54 MB -> Resident Set Size - total memory allocated for the process execution",
"heapTotal": "102.3 MB -> total size of the allocated heap",
"heapUsed": "94.3 MB -> actual memory used during the execution",
"external": "3.03 MB -> V8 external memory"
}
*/
如果你使用的是 express.js 框架,则可以使用 express-status-monitor。它非常易于集成,并以图形格式提供 CPU 使用率、内存使用率、响应时间等信息。
top
命令,并按 M 键(Shift+M)按照内存使用量排序进程。应用程序 > 实用工具
,您会找到一个名为 活动监视器
的应用程序。那个相当于任务管理器。OS X 也有 top
命令。 - Ingwie Phoenixhtop
代替top
,效果更佳。 - Ryan Shillington
--expose-gc
来调用gc
函数? - Rob W--expose-gc
来执行process.memoryUsage()
。在回答中,使用了gc()
(需要--expose-gc
)来有规律地触发垃圾收集以便更容易地查看process.memoryUsage
报告的内容。请注意不改变原文的意思,并尽可能使翻译通俗易懂。 - Rob W