• 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    h.digest(outEnc);
56  }
57
58  bench.end(gbits);
59}
60
61function streamWrite(algo, message, encoding, writes, len, outEnc) {
62  const written = writes * len;
63  const bits = written * 8;
64  const gbits = bits / (1024 * 1024 * 1024);
65
66  while (writes-- > 0) {
67    const h = crypto.createHash(algo);
68
69    if (outEnc !== 'buffer')
70      h.setEncoding(outEnc);
71
72    h.write(message, encoding);
73    h.end();
74    h.read();
75  }
76
77  bench.end(gbits);
78}
79