N
N
Nurzhan Bakibaev2011-10-13 14:39:32
C++ / C#
Nurzhan Bakibaev, 2011-10-13 14:39:32

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(&quot;%d\n&quot;, rand()%1000000);<br/>
}<br/>

and run the script
g++ gen.cpp -o gen<br/>
<br/>
for cnt in {1..100}<br/>
do<br/>
 ./gen<br/>
done<br/>

you can see that almost all values ​​are the same.
What is the best way to generate random numbers in C++ if the program runs 40-50 times per second?

Answer the question

In order to leave comments, you need to log in

4 answer(s)
Y
yeputons, 2011-10-13
@Hypuk

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);

This is what I do when I write test generators for stress testing tasks.

E
ertaquo, 2011-10-13
@ertaquo

Maybe so?

srand(clock());

E
Eol, 2011-10-13
@Eol

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 question

Ask a Question

731 491 924 answers to any question