C++ Logo

std-proposals

Advanced search

Re: Comments for P0205 and P2060: Mersenne twister can actually generate 7 and 13

From: Dimitrij Mijoski <dmjpp_at_[hidden]>
Date: Thu, 18 Nov 2021 00:24:08 +0100
Hello again,

On Wed, 2021-11-17 at 22:05 +0000, Lénárd Szolnoki via Std-Proposals
wrote:
> Hi,
>
> On Wed, 17 Nov 2021 18:26:41 +0000
> Dimitrij Mijoski via Std-Proposals <std-proposals_at_[hidden]>
> wrote:
>
> > I personally think that filling the whole state (624 integers) with
> > values from random_device is wrong because it wastes the system
> > entropy. If not wrong then slow and pointless. I consider the
> > following code to be bad.
> >
> > #include <random>
> > using namespace std;
> >
> > int main()
> > {
> > random_device rd;
> > unsigned int v[624]; // no need for this large seed
> > for(auto& a: v)
> > a = rd();
> > seed_seq sd(begin(v), end(v));
> > auto g = mt19937(sd);
> > }
>
> random_device random number sources by standard library:
> * libstdc++ : /dev/urandom by default
> * libc++ : getentropy() which uses getrandom()
> * MS STL : rand_s() which in turn uses RtlGenRandom()
>
> Reading from /dev/urandom or using getentropy() doesn't deplete OS
> entropy. I didn't find any documentation for rand_s(). However MS
> STL's
> random_device::entropy() just return 32, so my bet that it doesn't
> deplete entropy either.

Reading from the OS randomness pool always spends some entropy. It does
not depletes it, it just spends some. But if you get 624 random
integers from the OS just to get one integer from the PRNG you will
surely spend it faster. The thing with /dev/urandom is that it will not
block if all entropy is spent, it will fall back to a different
algorithm and it will return a number.

Even if we put the entropy discussion aside, there is the performance
aspect. Calling random device is slow because you do a system call
internally to the OS, and the OS might even do some IO. The number of
calls to random_device should be small.

Received on 2021-11-17 17:24:14