• 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: ['sha1', 'sha256', 'sha512'],
10  type: ['asc', 'utf', 'buf'],
11  len: [2, 1024, 102400, 1024 * 1024],
12  api: ['legacy', 'stream']
13});
14
15function main({ api, type, len, algo, writes }) {
16  if (api === 'stream' && /^v0\.[0-8]\./.test(process.version)) {
17    console.error('Crypto streams not available until v0.10');
18    // Use the legacy, just so that we can compare them.
19    api = 'legacy';
20  }
21
22  let message;
23  let encoding;
24  switch (type) {
25    case 'asc':
26      message = 'a'.repeat(len);
27      encoding = 'ascii';
28      break;
29    case 'utf':
30      message = 'ü'.repeat(len / 2);
31      encoding = 'utf8';
32      break;
33    case 'buf':
34      message = Buffer.alloc(len, 'b');
35      break;
36    default:
37      throw new Error(`unknown message type: ${type}`);
38  }
39
40  const fn = api === 'stream' ? streamWrite : legacyWrite;
41
42  bench.start();
43  fn(algo, message, encoding, writes, len);
44}
45
46function legacyWrite(algo, message, encoding, writes, len) {
47  const written = writes * len;
48  const bits = written * 8;
49  const gbits = bits / (1024 * 1024 * 1024);
50  const h = crypto.createHash(algo);
51
52  while (writes-- > 0)
53    h.update(message, encoding);
54
55  h.digest();
56
57  bench.end(gbits);
58}
59
60function streamWrite(algo, message, encoding, writes, len) {
61  const written = writes * len;
62  const bits = written * 8;
63  const gbits = bits / (1024 * 1024 * 1024);
64  const h = crypto.createHash(algo);
65
66  while (writes-- > 0)
67    h.write(message, encoding);
68
69  h.end();
70  h.read();
71
72  bench.end(gbits);
73}
74