C: A true random number generator

From FSDeveloper Wiki
Jump to: navigation, search

This random number generator is about as close as it gets to being truly random. It works by using the number of CPU cycles from startup as the seed. The downside is that intrin.h may not be available in a non-Microsoft compiler. The advantage of using this over the more usual time-seeded random number generator is that this can be used on succeeding code lines in a gauge and will return a different number from each line. A time-seeded random number generator will not have had time (!) to update and will give you the same 'random' number for a number of successive calls during a gauge update cycle.

iMin, iMax = the range of numbers to be randomised
#include <intrin.h>
#pragma intrinsic(__rdtsc)
// ---------------------------
// Random number generator
// ---------------------------
int getRand(int iMin,int iMax)
  unsigned __int64 i;

  i = __rdtsc();
  while (i < iMin);

  return (int)i;