std::random_device
may be expensive to create. It may open a device feeding it data, and that takes some time. It can also be expensive to call because it requires entropy to deliver a truly random number, not a pseudo random number.uniform_int_distribution
is never expensive to create. It’s designed to be cheap. It does have internal state though, so in extreme situations, keep the same distribution between calls if you can.- Pseudo-random number generators (PRNGs), like
default_random_engine
ormt19937
, are usually semi-cheap to create, but expensive to seed. How expensive this is largely depends on the size of the state they keep internally, and what the seeding procedure is. For example, thestd::mersenne_twister_engine
in the standard library keeps a “large” (leaning towards “huge”) state which makes it very expensive to create.
Upside:
- You usually only use one temporary
random_device
and call it once to seed one PRNG. So, one expensive creation and call torandom_device
and one expensive seeding of a PRNG.