• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1// Throughput benchmark
2// creates a single hasher, then pushes a bunch of data through it
3'use strict';
4const common = require('../common.js');
5const crypto = require('crypto');
6
7const bench = common.createBenchmark(main, {
8  writes: [500],
9  algo: [ 'sha256', 'md5' ],
10  type: ['asc', 'utf', 'buf'],
11  out: ['hex', 'binary', 'buffer'],
12  len: [2, 1024, 102400, 1024 * 1024],
13  api: ['legacy', 'stream']
14});
15
16function main({ api, type, len, out, writes, algo }) {
17  if (api === 'stream' && /^v0\.[0-8]\./.test(process.version)) {
18    console.error('Crypto streams not available until v0.10');
19    // Use the legacy, just so that we can compare them.
20    api = 'legacy';
21  }
22
23  let message;
24  let encoding;
25  switch (type) {
26    case 'asc':
27      message = 'a'.repeat(len);
28      encoding = 'ascii';
29      break;
30    case 'utf':
31      message = 'ü'.repeat(len / 2);
32      encoding = 'utf8';
33      break;
34    case 'buf':
35      message = Buffer.alloc(len, 'b');
36      break;
37    default:
38      throw new Error(`unknown message type: ${type}`);
39  }
40
41  const fn = api === 'stream' ? streamWrite : legacyWrite;
42
43  bench.start();
44  fn(algo, message, encoding, writes, len, out);
45}
46
47function legacyWrite(algo, message, encoding, writes, len, outEnc) {
48  const written = writes * len;
49  const bits = written * 8;
50  const gbits = bits / (1024 * 1024 * 1024);
51
52  while (writes-- > 0) {
53    const h = crypto.createHash(algo);
54    h.update(message, encoding);
55    let res = h.digest(outEnc);
56
57    // Include buffer creation costs for older versions
58    if (outEnc === 'buffer' && typeof res === 'string')
59      res = Buffer.from(res, 'binary');
60  }
61
62  bench.end(gbits);
63}
64
65function streamWrite(algo, message, encoding, writes, len, outEnc) {
66  const written = writes * len;
67  const bits = written * 8;
68  const gbits = bits / (1024 * 1024 * 1024);
69
70  while (writes-- > 0) {
71    const h = crypto.createHash(algo);
72
73    if (outEnc !== 'buffer')
74      h.setEncoding(outEnc);
75
76    h.write(message, encoding);
77    h.end();
78    h.read();
79  }
80
81  bench.end(gbits);
82}
83