我怎样才能标杆流中的Node.js?
我试过benchmark.js :
var fs = require('fs');
var Transform = require('readable-stream').Transform;
var util = require('util');
var Benchmark = require('benchmark');
var suite = new Benchmark.Suite;
// my super uppercase stream
function Uppercase(options) {
if (!(this instanceof Uppercase))
return new Uppercase(options);
Transform.call(this, options);
}
Uppercase.prototype = Object.create(
Transform.prototype, { constructor: { value: Uppercase }});
Uppercase.prototype._transform = function(chunk, encoding, done) {
chunk = chunk.toString().toUpperCase();
this.push(chunk)
};
// start benchmarking
suite.add('stream test', function() {
var reader = fs.createReadStream('in.txt');
var parser = new Uppercase();
var writer = fs.createWriteStream('out.txt');
reader.pipe(parser).pipe(writer);
})
// add listeners
.on('cycle', function(event) {
console.log(String(event.target));
})
.on('complete', function() {
console.log('Fastest is ' + this.filter('fastest').pluck('name'));
})
// run async
.run();
suite.run();
但我得到的错误
Unhandled stream error in pipe
您的代码遇到这个问题,你可以通过听错误的读者和作家看出来:
[Error: EMFILE, open 'out.txt'] errno: 20, code: 'EMFILE', path: 'in.txt'
[Error: EMFILE, open 'out.txt'] errno: 20, code: 'EMFILE', path: 'out.txt'
这是一个事实,即流是异步的,并且没有当他们结束对明确的回调引起的。 所以你几乎创造in.txt和out.txt之间一千,数千管流,直到系统会告诉你,他们有太多的文件描述符打开。
所以,我想通过“在节点标杆流”,你要要计算什么是需要做同步执行此操作的时间:
reader.pipe(filter).pipe(writer)
在这种情况下,你将需要:
- 使用基准的延迟选项benchmarkjs文档
- 可以肯定,当管作业结束的node.js文档
对于这个答案的代码已经过测试节点0.10.0,但我想这唯一的区别应该是在保持模块的名称Transform
:
var fs = require('fs');
var util = require('util');
var Transform = require('stream').Transform;
var Benchmark = require('benchmark');
var suite = new Benchmark.Suite;
var i = 0;
// my super uppercase stream
function Uppercase(options) {
if (!(this instanceof Uppercase))
return new Uppercase(options);
Transform.call(this, options);
}
Uppercase.prototype = Object.create(
Transform.prototype, { constructor: { value: Uppercase }}
);
Uppercase.prototype._transform = function(chunk, encoding, done) {
chunk = chunk.toString().toUpperCase();
this.push(chunk)
};
// start benchmarking
suite.add('stream test', {
'defer' : true,
'fn' : function (deferred) {
var reader = fs.createReadStream('in.txt');
var parser = new Uppercase();
var writer = fs.createWriteStream('out.txt');
reader.on('error', function (err) {
console.log(err);
});
writer.on('error', function (err) {
console.log(err);
});
reader.on('end', function (argument) {
// Wait until reader is over and then close reader and finish deferred test
writer.end();
deferred.resolve();
});
reader.pipe(parser).pipe(writer, {'end': false});
}
})
// listeners
.on('cycle', function(event) {
console.log(String(event.target));
})
.on('complete', function() {
console.log('Fastest is ' + this.filter('fastest').pluck('name'));
})
// run async
.run();