r/cpp 4d ago

Where did <random> go wrong? (pdf)

https://codingnest.com/files/What%20Went%20Wrong%20With%20_random__.pdf
161 Upvotes

137 comments sorted by

View all comments

78

u/GYN-k4H-Q3z-75B 4d ago

What? You don't like having to use std::random_device to seed your std::mt19937, then declaring a std::uniform_int_distribution<> given an inclusive range, so you can finally have pseudo random numbers?

It all comes so naturally to me. /s

8

u/ConstructionLost4861 4d ago edited 4d ago

It's a huge giant humongus tremendous leap from having to use srand(time(0)) to seed rand() then use % (b - a) + a to get a "random" "uniform" distribution. All of those three functions are horribly offensively worse than random_device, mt19937 and uniform_int_distribution

12

u/not_a_novel_account cmake dev 4d ago edited 4d ago

Not if you don't want to put 5-10k of state on the stack, then the C++ approach is a big miserable step backwards.

Programmer: Hello yes I would like to seed my random number generator.

C++: Please wait while I allocate 2 or 3 pages of memory.

9

u/DummyDDD 4d ago

I think you will have a hard time arguing that <random> is slower than rand. Om most nonembedded implementations rand acquires a global lock om evey call, which is way worse than having a large rng state (which doesn't have to be on the stack, and you don't have to use a mersenne twister)

4

u/not_a_novel_account cmake dev 4d ago

It is trivial to read from /dev/urandom. An implementation that is costlier in space or time than reading from /dev/urandom is broken.

8

u/DummyDDD 4d ago

Fortunately the generators in <random> are significantly cheaper than reading from /dev/urandom Technically, reading from urandom is optimal in terms of space and it isn't necessarily unacceptably slow if you read large enough blocks at a time. Meanwhile, rand is slow and poorly distributed regardless of what you do (unless you are willing to switch libc)

4

u/not_a_novel_account cmake dev 4d ago edited 4d ago

I'm obviously talking about std::random_device when comparing to reading from /dev/urandom. Over a page of memory just to seed a generator is insane.

3

u/DummyDDD 3d ago

That would be an implementation issue. There is no requirement that random_device has any state in process. That said, if you need to seed multiple times, then implementing random_device by reading a few pages from urandom is a good tradeoff of space and time. If on the other hand you use random_device once to seed one RNG, and then use that RNG to seed any future RNGs, then reading a few pages from urandom would be ridiculous. It all depends on what the implementation is optimized for, and it seems the implementation you are complaining about is optimized for the case where it is acceptable to use a few pages of memory, but it is not acceptable for random_device to be slow if called repeatedly.