Search code examples
c++randomprng

How can C/C++'s rand() generate random numbers so quickly?


My understanding is that a pseudo-random number generator basically just takes some number (the seed), hashes it with a bunch of XORs and bitshifts, and then spits out a really long number from which a remainder can be retrieved to get your "random" number.

Now, usually you'd use time(NULL) as the seed for rand() in C/C++. However, time(NULL) only increments every second, not every millisecond. So how, then, can I for loop over rand() a thousand times in less than one second and still get different numbers as outputs if the seed is still the same time(NULL) value?


Solution

  • rand() uses the previous random value as the new seed on subsequent calls. This is why a unique random sequence of values will be generated when you start with a different seed value.