|
| 1 | +'use strict'; |
| 2 | + |
| 3 | +const path = require('path'); |
| 4 | +const common = require('../common.js'); |
| 5 | +const filename = path.resolve(__dirname, '.removeme-benchmark-garbage'); |
| 6 | +const fs = require('fs'); |
| 7 | +const writeFile = fs.writeFile; |
| 8 | + |
| 9 | +const bench = common.createBenchmark(main, { |
| 10 | + dur: [5], |
| 11 | + file: [''], |
| 12 | + type: ['buf', 'asc', 'utf'], |
| 13 | + size: [2, 1024, 64 * 1024, 1024 * 1024] |
| 14 | +}); |
| 15 | + |
| 16 | +function main(conf) { |
| 17 | + const dur = +conf.dur * 1000; |
| 18 | + const size = +conf.size; |
| 19 | + const file = (conf.file.length === 0 ? filename : conf.file); |
| 20 | + var writes = 0; |
| 21 | + var ended = false; |
| 22 | + var encoding; |
| 23 | + var data; |
| 24 | + |
| 25 | + try { fs.unlinkSync(file); } catch (e) {} |
| 26 | + process.on('exit', function() { |
| 27 | + try { fs.unlinkSync(file); } catch (e) {} |
| 28 | + }); |
| 29 | + |
| 30 | + setTimeout(function() { |
| 31 | + bench.end(writes); |
| 32 | + ended = true; |
| 33 | + }, dur); |
| 34 | + |
| 35 | + switch (conf.type) { |
| 36 | + case 'buf': |
| 37 | + data = Buffer.alloc(size, 'b'); |
| 38 | + (function() { |
| 39 | + function afterWrite(err) { |
| 40 | + if (err) |
| 41 | + throw err; |
| 42 | + if (ended) |
| 43 | + return; |
| 44 | + ++writes; |
| 45 | + writeFile(file, data, afterWrite); |
| 46 | + } |
| 47 | + bench.start(); |
| 48 | + writeFile(file, data, afterWrite); |
| 49 | + })(); |
| 50 | + return; |
| 51 | + case 'asc': |
| 52 | + data = new Array(size + 1).join('a'); |
| 53 | + encoding = 'ascii'; |
| 54 | + break; |
| 55 | + case 'utf': |
| 56 | + data = new Array(Math.ceil(size / 2) + 1).join('ü'); |
| 57 | + encoding = 'utf8'; |
| 58 | + break; |
| 59 | + default: |
| 60 | + throw new Error('invalid type'); |
| 61 | + } |
| 62 | + |
| 63 | + (function() { |
| 64 | + function afterWrite(err) { |
| 65 | + if (err) |
| 66 | + throw err; |
| 67 | + if (ended) |
| 68 | + return; |
| 69 | + ++writes; |
| 70 | + writeFile(file, data, encoding, afterWrite); |
| 71 | + } |
| 72 | + bench.start(); |
| 73 | + writeFile(file, data, encoding, afterWrite); |
| 74 | + })(); |
| 75 | +} |
0 commit comments