-
Notifications
You must be signed in to change notification settings - Fork 30.7k
/
Copy pathhash-stream-throughput.js
73 lines (60 loc) · 1.71 KB
/
hash-stream-throughput.js
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
// Throughput benchmark
// creates a single hasher, then pushes a bunch of data through it
'use strict';
const common = require('../common.js');
const crypto = require('crypto');
const bench = common.createBenchmark(main, {
writes: [500],
algo: ['sha1', 'sha256', 'sha512'],
type: ['asc', 'utf', 'buf'],
len: [2, 1024, 102400, 1024 * 1024],
api: ['legacy', 'stream'],
});
function main({ api, type, len, algo, writes }) {
if (api === 'stream' && /^v0\.[0-8]\./.test(process.version)) {
console.error('Crypto streams not available until v0.10');
// Use the legacy, just so that we can compare them.
api = 'legacy';
}
let message;
let encoding;
switch (type) {
case 'asc':
message = 'a'.repeat(len);
encoding = 'ascii';
break;
case 'utf':
message = 'ü'.repeat(len / 2);
encoding = 'utf8';
break;
case 'buf':
message = Buffer.alloc(len, 'b');
break;
default:
throw new Error(`unknown message type: ${type}`);
}
const fn = api === 'stream' ? streamWrite : legacyWrite;
bench.start();
fn(algo, message, encoding, writes, len);
}
function legacyWrite(algo, message, encoding, writes, len) {
const written = writes * len;
const bits = written * 8;
const gbits = bits / (1024 * 1024 * 1024);
const h = crypto.createHash(algo);
while (writes-- > 0)
h.update(message, encoding);
h.digest();
bench.end(gbits);
}
function streamWrite(algo, message, encoding, writes, len) {
const written = writes * len;
const bits = written * 8;
const gbits = bits / (1024 * 1024 * 1024);
const h = crypto.createHash(algo);
while (writes-- > 0)
h.write(message, encoding);
h.end();
h.read();
bench.end(gbits);
}