如何监控 Node.js 的内存使用情况?
最佳答案
内置process模块有一个方法memoryUsage
它提供了对当前 Node.js 进程的内存使用情况的洞察。以下是 64 位系统上 Node v0.12.2 中的示例:
$ 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 }
在这个简单的示例中,您可以看到分配一个包含 10M 元素的数组消耗了大约 80MB(查看 heapUsed
)。
如果查看 V8 的源代码(Array::New
、Heap::AllocateRawFixedArray
、FixedArray::SizeFor
),您会发现数组使用的内存是一个固定值加上长度乘以指针大小。后者在 64 位系统上是 8 个字节,这证实了观察到的 8 x 10 = 80MB 的内存差异是有意义的。
关于javascript - 如何监控 Node.js 的内存使用情况?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20018588/