• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1// Call fs.readFile over and over again really fast.
2// Then see how many times it got called.
3// Yes, this is a silly benchmark.  Most benchmarks are silly.
4'use strict';
5
6const path = require('path');
7const common = require('../common.js');
8const fs = require('fs');
9const assert = require('assert');
10
11const tmpdir = require('../../test/common/tmpdir');
12tmpdir.refresh();
13const filename = path.resolve(tmpdir.path,
14                              `.removeme-benchmark-garbage-${process.pid}`);
15
16const bench = common.createBenchmark(main, {
17  duration: [5],
18  encoding: ['', 'utf-8'],
19  len: [1024, 16 * 1024 * 1024],
20  concurrent: [1, 10],
21});
22
23function main({ len, duration, concurrent, encoding }) {
24  try {
25    fs.unlinkSync(filename);
26  } catch {
27    // Continue regardless of error.
28  }
29  let data = Buffer.alloc(len, 'x');
30  fs.writeFileSync(filename, data);
31  data = null;
32
33  let reads = 0;
34  let benchEnded = false;
35  bench.start();
36  setTimeout(() => {
37    benchEnded = true;
38    bench.end(reads);
39    try {
40      fs.unlinkSync(filename);
41    } catch {
42      // Continue regardless of error.
43    }
44    process.exit(0);
45  }, duration * 1000);
46
47  function read() {
48    fs.readFile(filename, encoding, afterRead);
49  }
50
51  function afterRead(er, data) {
52    if (er) {
53      if (er.code === 'ENOENT') {
54        // Only OK if unlinked by the timer from main.
55        assert.ok(benchEnded);
56        return;
57      }
58      throw er;
59    }
60
61    if (data.length !== len)
62      throw new Error('wrong number of bytes returned');
63
64    reads++;
65    if (!benchEnded)
66      read();
67  }
68
69  while (concurrent--) read();
70}
71