C: A true random number generator

From FSDeveloper Wiki
Jump to navigationJump to 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.

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();
  do
    i=(int)rand()%iMax;
  while (i < iMin);

  return (int)i;
}