File: hash-stream-creation.js

package info (click to toggle)
nodejs 4.8.2~dfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 62,476 kB
  • ctags: 111,183
  • sloc: cpp: 661,544; ansic: 31,406; python: 23,073; makefile: 1,418; sh: 1,384; perl: 255; lisp: 222; ruby: 76; xml: 50
file content (84 lines) | stat: -rw-r--r-- 2,101 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
// throughput benchmark
// creates a single hasher, then pushes a bunch of data through it
'use strict';
var common = require('../common.js');
var crypto = require('crypto');

var bench = common.createBenchmark(main, {
  writes: [500],
  algo: [ 'sha256', 'md5' ],
  type: ['asc', 'utf', 'buf'],
  out: ['hex', 'binary', 'buffer'],
  len: [2, 1024, 102400, 1024 * 1024],
  api: ['legacy', 'stream']
});

function main(conf) {
  var api = conf.api;
  if (api === 'stream' && process.version.match(/^v0\.[0-8]\./)) {
    console.error('Crypto streams not available until v0.10');
    // use the legacy, just so that we can compare them.
    api = 'legacy';
  }

  var message;
  var encoding;
  switch (conf.type) {
    case 'asc':
      message = new Array(conf.len + 1).join('a');
      encoding = 'ascii';
      break;
    case 'utf':
      message = new Array(conf.len / 2 + 1).join('ΓΌ');
      encoding = 'utf8';
      break;
    case 'buf':
      message = new Buffer(conf.len);
      message.fill('b');
      break;
    default:
      throw new Error('unknown message type: ' + conf.type);
  }

  var fn = api === 'stream' ? streamWrite : legacyWrite;

  bench.start();
  fn(conf.algo, message, encoding, conf.writes, conf.len, conf.out);
}

function legacyWrite(algo, message, encoding, writes, len, outEnc) {
  var written = writes * len;
  var bits = written * 8;
  var gbits = bits / (1024 * 1024 * 1024);

  while (writes-- > 0) {
    var h = crypto.createHash(algo);
    h.update(message, encoding);
    var res = h.digest(outEnc);

    // include buffer creation costs for older versions
    if (outEnc === 'buffer' && typeof res === 'string')
      res = new Buffer(res, 'binary');
  }

  bench.end(gbits);
}

function streamWrite(algo, message, encoding, writes, len, outEnc) {
  var written = writes * len;
  var bits = written * 8;
  var gbits = bits / (1024 * 1024 * 1024);

  while (writes-- > 0) {
    var h = crypto.createHash(algo);

    if (outEnc !== 'buffer')
      h.setEncoding(outEnc);

    h.write(message, encoding);
    h.end();
    h.read();
  }

  bench.end(gbits);
}