Summary: I need a simple self-contained way to seed my RNG so that the seed is different every time the program is launched.
Details:
I often need to run the same program (which does calculations with random numbers, e.g. Monte Carlo simulation etc.) many times to have good statistics on the result. In this case it is important that the random number generator will have a different seed on each run.
I would like to have a simple, cross-platform solution for this that can be contained within the program itself. (I.e. I don't want to always go to the trouble of having a script that launches each instance of the program with a different seed parameter.)
Note that using time(0)
as a seed is not a good solution because the timer resolution is bad: if several processes are launched in parallel, they are likely to get the same seed from time(0)
.
Requirements:
- as simple as possible
- cross platform (currently I need it to work on Windows & Linux, x86 & x64 only).
- self contained: shouldn't rely on a special way of launching the program (passing the seed as a parameter from the launch script is too much trouble).
- I'd like to wrap the whole thing into a small library that I can include in any new project with minimal effort and just do something like
SeedMyRNG(getSeed());
EDIT:
Although my main question was about doing this in C (or C++), based on the pointers provided in the answer I found os.urandom()
as a Python solution (which is also useful for me).
Related relevant question: How to use /dev/random or urandom in C?