【问题标题】:node process memory usage, resident set size constantly increasing节点进程内存使用,驻留集大小不断增加
【发布时间】:2015-03-21 17:13:34
【问题描述】:

来自What do the return values of node.js process.memoryUsage() stand for? RSS 是驻留集大小,进程内存中保存在 RAM 中的部分 (此进程在 RAM 中保留了多少内存,以字节为单位)示例中使用的“text.txt”文件大小为 370KB(378880 字节)

var http    = require('http');
var fs      = require('fs');
var express = require('express');
var app     = express();

console.log("On app bootstrap = ", process.memoryUsage());

app.get('/test', function(req, res) {

    fs.readFile(__dirname + '/text.txt', function(err, file) {
        console.log("When File is available = ", process.memoryUsage());
        res.end(file);

    });

    setTimeout(function() {
        console.log("After sending = ", process.memoryUsage());
    }, 5000);

});

app.listen(8081);

所以在应用引导程序上:{ rss: 22069248, heapTotal: 15551232, heapUsed: 9169152 } 在我对“/test”提出 10 次请求后,情况是:

When File is available =  { rss: 33087488, heapTotal: 18635008, heapUsed: 6553552 }
After sending          =  { rss: 33447936, heapTotal: 18635008, heapUsed: 6566856 }

所以从应用程序 boostrap 到 10nth 请求 rss 增加了 11378688 字节,大约是 text.txt 文件大小的 30 倍。

我知道在将结果写回客户端之前,此代码会将每个请求的整个 data.txt 文件缓冲到内存中,但我希望在请求完成后,“text.txt”占用的内存将被释放? 但事实并非如此?

第二如何设置节点进程可以消耗的最大RAM内存大小?

【问题讨论】:

  • 所以我注释掉了 fs.readFile 部分,这些是日志,第一个 req After sending = { rss: 31162368, heapTotal: 18862880, heapUsed: 10961672 } 10th req After sending = { rss: 31596544, heapTotal: 18862880, heapUsed: 11393584 } 就像 424kb,非常有线,我也在寻找答案。编辑:找到这个stackoverflow.com/questions/16441601/…

标签: node.js


【解决方案1】:

在 js 中,垃圾收集器不会在您的代码执行后立即运行。因此内存不会在执行后立即释放。如果您关心内存消耗,您可以在处理大对象后独立运行 GC。更多信息您可以找到here

setTimeout(function() {
    global.gc();
    console.log("After sending = ", process.memoryUsage());
}, 5000);

要查看您的内存分配,您可以使用 v8-profiler 运行您的服务器并获取堆快照。更多信息here

【讨论】:

  • 请注意,要让gc 暴露给您的程序,您可能必须以node --expose-gc 启动节点。
【解决方案2】:

尝试再次运行您的示例并给进程一些时间来运行垃圾收集。使用系统监视器密切关注进程的内存使用情况,一段时间后应该会清除。如果它没有停止,则进程的内存使用量不会比下面提到的高。

根据node documentation,内存限制为 32 位 512 mb 和 64 位 1 gb。如有必要,可以增加它们。

【讨论】:

    猜你喜欢
    • 2020-12-21
    • 2023-03-09
    • 2015-02-10
    • 2020-03-02
    • 2014-11-20
    • 2011-12-01
    • 2015-02-17
    • 2017-04-02
    相关资源
    最近更新 更多