Merge remote-tracking branch 'origin/v0.8'
[platform/upstream/nodejs.git] / benchmark / fs-write-stream-throughput.js
1
2 // If there are no args, then this is the root.  Run all the benchmarks!
3 if (!process.argv[2])
4   parent();
5 else
6   runTest(+process.argv[2], +process.argv[3], process.argv[4]);
7
8 function parent() {
9   var types = [ 'string', 'buffer' ];
10   var durs = [ 1, 5 ];
11   var sizes = [ 1, 10, 100, 2048, 10240 ];
12   var queue = [];
13   types.forEach(function(t) {
14     durs.forEach(function(d) {
15       sizes.forEach(function(s) {
16         queue.push([__filename, d, s, t]);
17       });
18     });
19   });
20
21   var spawn = require('child_process').spawn;
22   var node = process.execPath;
23
24   run();
25
26   function run() {
27     var args = queue.shift();
28     if (!args)
29       return;
30     var child = spawn(node, args, { stdio: 'inherit' });
31     child.on('close', function(code, signal) {
32       if (code)
33         throw new Error('Benchmark failed: ' + args.slice(1));
34       run();
35     });
36   }
37 }
38
39 function runTest(dur, size, type) {
40   if (type !== 'string')
41     type = 'buffer';
42   switch (type) {
43     case 'string':
44       var chunk = new Array(size + 1).join('a');
45       break;
46     case 'buffer':
47       var chunk = new Buffer(size);
48       chunk.fill('a');
49       break;
50   }
51
52   var writes = 0;
53   var fs = require('fs');
54   try { fs.unlinkSync('write_stream_throughput'); } catch (e) {}
55
56   var start
57   var end;
58   function done() {
59     var time = end[0] + end[1]/1E9;
60     var written = fs.statSync('write_stream_throughput').size / 1024;
61     var rate = (written / time).toFixed(2);
62     console.log('fs_write_stream_dur_%d_size_%d_type_%s: %d',
63                 dur, size, type, rate);
64
65     try { fs.unlinkSync('write_stream_throughput'); } catch (e) {}
66   }
67
68   var f = require('fs').createWriteStream('write_stream_throughput');
69   f.on('drain', write);
70   f.on('open', write);
71   f.on('close', done);
72
73   // streams2 fs.WriteStreams will let you send a lot of writes into the
74   // buffer before returning false, so capture the *actual* end time when
75   // all the bytes have been written to the disk, indicated by 'finish'
76   f.on('finish', function() {
77     end = process.hrtime(start);
78   });
79
80   var ending = false;
81   function write() {
82     // don't try to write after we end, even if a 'drain' event comes.
83     // v0.8 streams are so sloppy!
84     if (ending)
85       return;
86
87     start = start || process.hrtime();
88     while (false !== f.write(chunk));
89     end = process.hrtime(start);
90
91     if (end[0] >= dur) {
92       ending = true;
93       f.end();
94     }
95   }
96 }