From: Jérôme Benoit Date: Tue, 21 Sep 2021 12:20:39 +0000 (+0200) Subject: Add benchmark for random integer generation code X-Git-Url: https://git.piment-noir.org/?a=commitdiff_plain;h=aa697b2fb25ad4f2504dfc2a67ecd03d4e58fc77;p=benchmarks-js.git Add benchmark for random integer generation code Signed-off-by: Jérôme Benoit --- 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()