Most modern computers exhibit non deterministic behavior, what makes impossible to tell how many clock cycles will occur between two consecutive calls to read the computer clock.
The following code is a pseudo random number generator for one byte using the computer clock.
unsigned long occurrences = 0;
unsigned long total = 0;
while (true) {
if ((clock() & 0xFF) == 60) // testing ocurrences for a given number, 60 for instance
occurrences++;
total++;
printf("%f\n", (float)occurrences / (float)total ); // this should be approximately 1/256 = 0.00390625
}
Excluding serious applications like encription for instance, it could be used in mobile platforms for games.
I wonder what could be the advantages and disadvantages of such implementation.
You are missing the proper way to use
rand()or, more specifically,srand().You need to call
srand()exactly once during program run.Do not call
srand()in a loop.Do not call
srand()before each call torand().The best way to ensure proper
srand()management is to call it once inside yourmain()function and then forget about it: just userand()afterwards.