Thursday, August 26, 2010

Simple Random Number Generator

Today i decided to write my own rand function to generate a random number without any  use of the time APIs. Unlike the famous "rand" function, the "myrand" function doesn't require any srand function calls.

My function depends on an x-86 instruction called RDTSC. This instruction reads the processor time stamp i.e. the number of clock cycles since the last reset. The time stamp is read into the  EAX:EDX registers.

The "myrand" function takes only one parameter called X e.g. if X is 5, the generated random number will range from 0 to 4.

The code is so simple that it can be implemented in few lines.


int myrand(int X)
{
          int a;
         __asm
       {
                pushad
                rdtsc
               mov a,eax
               popad
       }
       return a%X;
}

The cons. for this function is that there is no guarantee that the target processor supports it, but i see it as a good step towards writing my self-implemented function.

Any ideas or comments are very welcome.

1 comment:

  1. Actually a very creative way of implementing your own random generator.
    Please keep up the great work.

    Regards

    ReplyDelete