Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ need a good technique for seeding rand() that does not use time()

I have a bash script that starts many client processes. These are AI game players that I'm using to test a game with many players, on the order of 400 connections.

The problem I'm having is that the AI player uses

srand( time(nullptr) );

But if all the players start at approximately the same time, they will frequently receive the same time() value, which will mean that they are all on the same rand() sequence.

Part of the testing process is to ensure that if lots of clients try to connect at approximately the same time, the server can handle it.

I had considered using something like

srand( (int) this );

Or similar, banking on the idea that each instance has a unique memory address.

Is there another better way?

like image 765
Eyelash Avatar asked Jun 03 '18 00:06

Eyelash


1 Answers

Use a random seed to a pseudorandom generator.

std::random_device is expensive random data. (expensive as in slow) You use that to seed a prng algorithm. mt19937 is the last prng algorithm you will ever need.

You can optionally follow that up by feeding it through a distribution if your needs require it. i.e. if you need values in a certain range other than what the generator provides.

std::random_device rd;
std::mt19937 generator(rd());
like image 129
Taekahn Avatar answered Oct 16 '22 05:10

Taekahn