Commit | Line | Data |
---|---|---|
aa697b2f JB |
1 | const Benchmark = require('benchmark') |
2 | const crypto = require('crypto') | |
3 | const { LIST_FORMATTER } = require('./benchmark-utils') | |
4 | ||
5 | const suite = new Benchmark.Suite() | |
6 | ||
7 | const maximum = 1000 | |
8 | ||
9 | /** | |
10 | * | |
11 | */ | |
12 | function secureRandom () { | |
13 | return crypto.randomBytes(4).readUInt32LE() / 0x100000000 | |
14 | } | |
15 | ||
16 | /** | |
17 | * @param max | |
18 | * @param min | |
19 | */ | |
20 | function getSecureRandomInteger (max, min = 0) { | |
21 | max = Math.floor(max) | |
22 | if (min) { | |
23 | min = Math.ceil(min) | |
24 | return Math.floor(secureRandom() * (max - min + 1)) + min | |
25 | } | |
26 | return Math.floor(secureRandom() * (max + 1)) | |
27 | } | |
28 | ||
29 | /** | |
30 | * @param max | |
31 | * @param min | |
32 | */ | |
33 | function getRandomInteger (max, min = 0) { | |
34 | max = Math.floor(max) | |
35 | if (min) { | |
36 | min = Math.ceil(min) | |
37 | return Math.floor(Math.random() * (max - min + 1)) + min | |
38 | } | |
39 | return Math.floor(Math.random() * (max + 1)) | |
40 | } | |
41 | ||
42 | suite | |
43 | .add('Secure random integer generator', function () { | |
44 | getSecureRandomInteger(maximum) | |
45 | }) | |
46 | .add('Random integer generator', function () { | |
47 | getRandomInteger(maximum) | |
48 | }) | |
49 | .on('cycle', function (event) { | |
50 | console.log(event.target.toString()) | |
51 | }) | |
52 | .on('complete', function () { | |
53 | console.log( | |
54 | 'Fastest is ' + LIST_FORMATTER.format(this.filter('fastest').map('name')) | |
55 | ) | |
56 | // eslint-disable-next-line no-process-exit | |
57 | process.exit() | |
58 | }) | |
59 | .run() |