From aa697b2fb25ad4f2504dfc2a67ecd03d4e58fc77 Mon Sep 17 00:00:00 2001 From: =?utf8?q?J=C3=A9r=C3=B4me=20Benoit?= Date: Tue, 21 Sep 2021 14:20:39 +0200 Subject: [PATCH] Add benchmark for random integer generation code MIME-Version: 1.0 Content-Type: text/plain; charset=utf8 Content-Transfer-Encoding: 8bit Signed-off-by: Jérôme Benoit --- package.json | 1 + random.js | 59 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 60 insertions(+) create mode 100644 random.js diff --git a/package.json b/package.json index 63ad06c..6983e57 100644 --- a/package.json +++ b/package.json @@ -11,6 +11,7 @@ "benchmark:quick-select": "node quick-select.js", "benchmark:promise-handling": "node promise-handling.js", "benchmark:fibonacci": "node fibonacci.js", + "benchmark:random": "node random.js", "format": "prettier --loglevel silent --write .; prettierx --write .", "lint": "eslint .", "lint:fix": "eslint . --fix", diff --git a/random.js b/random.js new file mode 100644 index 0000000..4b41596 --- /dev/null +++ b/random.js @@ -0,0 +1,59 @@ +const Benchmark = require('benchmark') +const crypto = require('crypto') +const { LIST_FORMATTER } = require('./benchmark-utils') + +const suite = new Benchmark.Suite() + +const maximum = 1000 + +/** + * + */ +function secureRandom () { + return crypto.randomBytes(4).readUInt32LE() / 0x100000000 +} + +/** + * @param max + * @param min + */ +function getSecureRandomInteger (max, min = 0) { + max = Math.floor(max) + if (min) { + min = Math.ceil(min) + return Math.floor(secureRandom() * (max - min + 1)) + min + } + return Math.floor(secureRandom() * (max + 1)) +} + +/** + * @param max + * @param min + */ +function getRandomInteger (max, min = 0) { + max = Math.floor(max) + if (min) { + min = Math.ceil(min) + return Math.floor(Math.random() * (max - min + 1)) + min + } + return Math.floor(Math.random() * (max + 1)) +} + +suite + .add('Secure random integer generator', function () { + getSecureRandomInteger(maximum) + }) + .add('Random integer generator', function () { + getRandomInteger(maximum) + }) + .on('cycle', function (event) { + console.log(event.target.toString()) + }) + .on('complete', function () { + console.log( + 'Fastest is ' + LIST_FORMATTER.format(this.filter('fastest').map('name')) + ) + // eslint-disable-next-line no-process-exit + process.exit() + }) + .run() -- 2.34.1