node/benchmark/crypto/hash-stream-throughput.js

74 lines
1.7 KiB
JavaScript
Raw Permalink Normal View History

// Throughput benchmark
2013-04-30 21:50:21 +00:00
// creates a single hasher, then pushes a bunch of data through it
'use strict';
const common = require('../common.js');
const crypto = require('crypto');
2013-04-30 21:50:21 +00:00
const bench = common.createBenchmark(main, {
2013-04-30 21:50:21 +00:00
writes: [500],
algo: ['sha1', 'sha256', 'sha512'],
2013-04-30 21:50:21 +00:00
type: ['asc', 'utf', 'buf'],
len: [2, 1024, 102400, 1024 * 1024],
api: ['legacy', 'stream'],
2013-04-30 21:50:21 +00:00
});
function main({ api, type, len, algo, writes }) {
if (api === 'stream' && /^v0\.[0-8]\./.test(process.version)) {
2013-04-30 21:50:21 +00:00
console.error('Crypto streams not available until v0.10');
// Use the legacy, just so that we can compare them.
2013-04-30 21:50:21 +00:00
api = 'legacy';
}
let message;
let encoding;
switch (type) {
2013-04-30 21:50:21 +00:00
case 'asc':
message = 'a'.repeat(len);
2013-04-30 21:50:21 +00:00
encoding = 'ascii';
break;
case 'utf':
message = 'ü'.repeat(len / 2);
2013-04-30 21:50:21 +00:00
encoding = 'utf8';
break;
case 'buf':
message = Buffer.alloc(len, 'b');
2013-04-30 21:50:21 +00:00
break;
default:
throw new Error(`unknown message type: ${type}`);
2013-04-30 21:50:21 +00:00
}
const fn = api === 'stream' ? streamWrite : legacyWrite;
2013-04-30 21:50:21 +00:00
bench.start();
fn(algo, message, encoding, writes, len);
2013-04-30 21:50:21 +00:00
}
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);
2013-04-30 21:50:21 +00:00
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);
2013-04-30 21:50:21 +00:00
while (writes-- > 0)
h.write(message, encoding);
h.end();
h.read();
bench.end(gbits);
}