0

Its looks like the follow RANDOM implementation are the fastest one:

my_random=RANDOM # 15 bit
echo $my_random

The follow other variants are know, but are much slower:

my_rnd=$((RANDOM<<15|RANDOM)) # 30 bit
my_rnd=$(((RANDOM<<15|RANDOM)<<15|RANDOM)) # 45 bit
my_rnd=$(( (RANDOM << 17) | (RANDOM << 2) | (RANDOM & 3) )) # 32 bit
my_rnd=$(( ((RANDOM<<30) | (RANDOM<<15) | RANDOM) & 0xffffffff )) # 32 Bit
my_rnd="$((0x$(dd if=/dev/urandom of=/dev/stdout bs=4 count=1 status=none | xxd -p)))" # possible 32 bit
my_rnd=( $(od -vAn -N4 -tu4 < /dev/urandom) ) # 32 Bit
my_rnd=$(shuf -rn 1 -i "0-4294967295") # 32 Bit
my_rnd=$(openssl rand 4 | od -DAn) # possible 32 bit

Unknown speed:

my_rnd=SRANDOM # 32 Bit # no system available for testing
my_rnd=$(date +%s%N | cut -b10-19) # not working one

Whats the fasted bash alternate, implementation or possible improvement for generating random numbers by RANDOM ? Solutions for 32 Bit are prefered.

Is really the worst solution the best ?

Its not looked for:

  • Solution which based on Python, Pearl, C and so on.
Alfred.37
  • 110
  • 1
  • 19
  • Related - [Search for "random numbers" on this site](https://www.google.com/search?q=site%3Aunix.stackexchange.com+random+numbers) – roaima Jul 22 '21 at 12:41
  • @roaima, the tested alternate slutions are much slower. – Alfred.37 Jul 22 '21 at 12:42
  • Related - [Using /dev/random, /dev/urandom to generate random data](https://unix.stackexchange.com/q/268952/100397) – roaima Jul 22 '21 at 12:42
  • @roaima, This is good, it describes how to measure the execution time. – Alfred.37 Jul 22 '21 at 12:49
  • 1
    What do you mean by "fastest"? Do you want a single random number, or a million? If you want a single one, then it shouldn't really matter what algorithm you use out of the ones you list. If you want a million (e.g. in a loop), then the shell is the _wrong language_ for you to be using for your application. Also, benchmarks will often depend on hardware, so the "fastest" on one system may well be not the fastest on another, depending on the hardware and the underlying libraries used. Do your own benchmarking. – Kusalananda Jul 22 '21 at 12:51

0 Answers0