Home > Software design >  Why is random device creation expensive?
Why is random device creation expensive?

Time:06-11

C 11 support pseudo-random number generation through <random> library. I've seen multiple books which mention that it is quite expensive to keep constructing and destroying std::random_device, std::uniform_int_distribution<>,
std::uniform_real_distribution<> objects and they recommend to keep a single copy of these objects in the application.

Why it is expensive to create/destroy these objects? And what exactly mean by expensive here? Is it expensive in terms of execution speed or executable size or any other thing?

Can someone please provide some explanation. Thanks.

CodePudding user response:

  • std::random_device does have to be expensive to create. It may open a device feeding it data and that takes some time. It can be expensive to call it though because in requires entropy to deliver a random number. Not a pseudo random number.
  • uniform_int_distribution is never expensive to create. It's designed to be cheap.
  • Any pseudo random number generator (PRNG), like default_random_engine or mt19937 are semi-cheap to create but expensive to seed.

Upside:

  • You usually only use one temporary random_device and call it once to seed one PRNG. So, one expensive creation and call to random_device and once expensive seeding of a PRNG.

CodePudding user response:

random_device has to interact with the operating system. This may have to do things such as opening file handles. For example a plain UNIX implementation may open the pseudo file /dev/urandom and read random bytes from that.

That also begs the question of how many bytes are to be read. Reading just as many as requested keeps the entropy pool of the OS full but involves a new system call for every invocation. A buffered read could waste the entropy if it is not used before the device is closed, causing the whole system to suffer.

This is why it is recommended to use the random_device only to initialize a pseudo-random number generator and then draw bytes from that. In other words: If you plug the random_device into a uniform_int_distribution you're probably doing it wrong and your server admin may strangle you.

  • Related