Answer the question
In order to leave comments, you need to log in
C++: Initializing srand?
What is the best way to initialize srand in C++?
I've always used srand( time(NULL) ), but this method doesn't work when the program is run many times in the same second.
For example, if we take such a program
int main(int argc, char** argv){<br/>
srand( time(0) );<br/>
printf("%d\n", rand()%1000000);<br/>
}<br/>
g++ gen.cpp -o gen<br/>
<br/>
for cnt in {1..100}<br/>
do<br/>
./gen<br/>
done<br/>
Answer the question
In order to leave comments, you need to log in
More options:
1. On Linux, you can read the first four bytes from /dev/urandom
2. On x86/x64, you can use the 'rdtsc' command - returns the number of processor cycles from the system start. Code for GCC:
long long x;
asm("rdtsc" : "=A"(x));
srand(x);
An option is to use gettimeofday(). It will return a struct timeval from which you can get microseconds :)
POSIX-2008 marks gettimeofday as deprecated, clock_gettime() can be used similarly instead.
PS. This is about POSIX systems, on Windows it's not a fact that there is.
P.P.S. And what about C++?
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question