【问题标题】:is something wrong with how I read tgz files in Node.js? Benchmark says it is slow :(我在 Node.js 中读取 tgz 文件的方式有问题吗?基准测试说它很慢:(
【发布时间】:2013-06-17 16:24:23
【问题描述】:

我的功能的基准:

mark@ichikawa:~/inbox/D3/read_logs$ time python countbytes.py
bytes: 277464

real    0m0.037s
user    0m0.036s
sys     0m0.000s
mark@ichikawa:~/inbox/D3/read_logs$ time node countbytes.js 
bytes: 277464

real    0m0.144s
user    0m0.120s
sys     0m0.032s

测量是在 Ubuntu 13.04 x86_64 位机器上进行的。

这是我的基准测试的简单版本(我也进行了 1000 次迭代)。我展示了我为读取 tgz 文件而编写的函数所花费的时间是我用 Python 编写的函数的 3 倍以上。

对于 1000 次迭代,文件大小为 277kB(我使用了 process.hrtime 和 timeit):

Node:   30.608409032000015
Python:  6.84210395813

1000 次迭代大小为 9.7MB:

Node:   590.491709309999
Python: 200.796745062

如果您对如何加快读取 tgz 文件有任何想法,请告诉我。

代码如下:

var fs = require('fs');
var tar = require('tar');
var zlib = require('zlib');
var Stream = require('stream');


var countBytes = new Stream;
countBytes.writable = true;
countBytes.count = 0;
countBytes.bytes = 0;

countBytes.write = function (buf) {
    countBytes.bytes += buf.length;
};

countBytes.end = function (buf) {
    if (arguments.length) countBytes.write(buf);

    countBytes.writable = false;
    console.log('bytes: ' + countBytes.bytes);
};

countBytes.destroy = function () {
    countBytes.writable = false;
};


fs.createReadStream('supercars-logs-13060317.tgz')
    .pipe(zlib.createUnzip())
    .pipe(tar.Extract({path: "responsetimes.log.13060317"}))
    .pipe(countBytes);

知道如何加快速度吗?

【问题讨论】:

  • supercars-logs-13060317.tgz 有多大?您是否尝试过在不同大小的文件上比较它们?
  • 我很想知道时间差是增加还是保持不变,对于更大的文件大约需要 25 秒。这应该告诉您是提取本身速度较慢还是提取所涉及的开销。
  • 对比一下,Python代码是什么样子的?

标签: javascript performance node.js file-io stream


【解决方案1】:

我看起来不错,但我很好奇为什么要使用tar 流?

我会使用 Transform 来实现 countBytes。我喜欢你用through2这个

var fs = require('fs')
, tar = require('tar')
, zlib = require('zlib')
, thr = require('through2')
, cache = {bytes: 0}
;
fs.createReadStream('supercars-logs-13060317.tgz')
  .pipe(zlib.createUnzip())
  .pipe(thr(function(chunk, enc, next){
    cache.bytes += chunk.length
    next(null, chunk)
  }))
  .on('end', function(){
    console.log(cache.count)
  })

【讨论】:

  • 我不确定您是否注意到这个问题已经存在将近一年了。关于 tar 我认为它最初是为了在磁带上写入文件而发明的。我们仍然在 Linux 上大量使用它。通常,在我的情况下,读取操作是基于文件而不是整个存档完成的。看起来它仍然是在 nodejs 中推荐的方法:stackoverflow.com/questions/21989460/…。只是出于好奇,您的解决方案是否比我的更快?
猜你喜欢
  • 2021-04-14
  • 1970-01-01
  • 2015-10-14
  • 2012-05-14
  • 2012-05-09
  • 2021-02-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多