1 import { randomInt } from 'node:crypto'
3 import { bench, group, run } from 'tatami-ng'
7 secureRandomWithRandomValues,
8 } from './benchmark-utils.mjs'
10 const maximum = 281474976710655
17 function getSecureRandomInteger (max = Number.MAX_SAFE_INTEGER, min = 0) {
18 if (max < min || max < 0 || min < 0) {
19 throw new RangeError('Invalid interval')
24 return Math.floor(secureRandom() * (max - min + 1)) + min
26 return Math.floor(secureRandom() * (max + 1))
34 function getSecureRandomIntegerWithRandomValues (
35 max = Number.MAX_SAFE_INTEGER,
38 if (max < min || max < 0 || min < 0) {
39 throw new RangeError('Invalid interval')
44 return Math.floor(secureRandomWithRandomValues() * (max - min + 1)) + min
46 return Math.floor(secureRandomWithRandomValues() * (max + 1))
54 function getRandomInteger (max = Number.MAX_SAFE_INTEGER, min = 0) {
55 if (max < min || max < 0 || min < 0) {
56 throw new RangeError('Invalid interval')
61 return Math.floor(Math.random() * (max - min + 1)) + min
63 return Math.floor(Math.random() * (max + 1))
66 group('Random Integer Generator', () => {
67 bench('Secure random integer generator', () => {
68 getSecureRandomInteger(maximum)
70 bench('Secure random with getRandomValues() integer generator', () => {
71 getSecureRandomIntegerWithRandomValues(maximum)
73 bench('Crypto random integer generator', () => {
76 bench('Math random integer generator', () => {
77 getRandomInteger(maximum)