如何监控 Node.js 的内存使用情况?
如何监控 Node.js 的内存使用情况?
IT技术
javascript
node.js
memory
2021-02-22 12:01:03
6个回答
内置的processmodule有一个方法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 内存差异是有道理的。
node-memwatch:检测和查找 Node.JS 代码中的内存泄漏。检查本教程跟踪 Node.js 中的内存泄漏
最初的memwatch基本上已经死了。试试memwatch-next,它似乎在现代版本的Node.js上运行良好。
您可以使用 node.js 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"
}
*/
其它你可能感兴趣的问题