Improved Seed/srand 

Introduction

If you have ever used the standard C runtime function, srand(time(NULL)) as a seed for the rnd() function, then you've probably noticed that it isn't very efficient. Therefore, in this article, I present to you what I believe to be a improvement over those functions. 

How it works

The function time(NULL) gets the system time by returning number of seconds elapsed since midnight (00:00:00), January 1, 1970. Since the time() function deals in a granularity of seconds, my idea was to replace this function with something that works in milliseconds. That way, I could reduce the time it takes for the value to change and for the completion of its cycle before restarting. 

For demo purposes, I've created a console application. However, this code will work in any C or C++ environment. Simply copy the code below and paste it into your application. In addition, I've commented out that standard srand call so that you can uncomment it and compare the two approaches with regards to performance. 

I haven't done a tremendous amount of research as to whether there are any drawbacks regarding my approach, However, if you do find something, or have any feedback at all, I'd be glad to hear from you. 

Code

// ----------------------------------------

#include // stdout

#include // time()

#include // rand() and srand()

#include // _ftime()

void SetSeed();

void main()

{

 //srand(time(NULL)); // the common way

 SetSeed();

 int randnum = rand () % 1501;

 cout << "seedtest range 0-1500 : " << randnum << endl;

}

void SetSeed()

{

 struct _timeb timebuf;  // struct to store timeinfo in

 _ftime(&timebuf);   // fill the struct with current time

 srand(timebuf.millitm); // use millisecs as seed

}

// ----------------------------------------