[英]How to monitor the memory usage of Node.js?
如何监控 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 内存差异是有道理的。
node-memwatch :检测和查找 Node.JS 代码中的内存泄漏。 检查本教程跟踪 Node.js 中的内存泄漏
最初的memwatch基本上已经死了。 尝试使用memwatch-next ,它似乎在现代版本的Node.js上运行良好。
您可以使用 node.jsmemoryUsage
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"
}
*/
在 Linux/Unix(注意:Mac OS 是 Unix)上,使用top
并按 M ( Shift + M ) 按内存使用情况对进程进行排序。
在 Windows 上使用任务管理器。
如果您使用 express.js 框架,那么您可以使用express-status-monitor 。 它非常易于集成,并以图形格式提供 CPU 使用率、内存使用率、响应时间等。
node memwatch 和 memwatch next 这些在 nodejs 14.17.0 版本上不受支持。 仅支持新的 node-memwatch-new 模块。 请告诉我如何在 nodejs 14.17 版本上安装 node-memwatch install。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.