Boost logo

Boost Users :

Subject: Re: [Boost-users] Random: How to get a different seed?
From: Lasse Kliemann (lasse-list-boost-users-2011_at_[hidden])
Date: 2011-01-24 15:57:59


* Message by -Cedric Laczny- from Mon 2011-01-24:

> I use this approach:
>
> #include <ctime>
> #include <time.h>
> #include <sys/time.h>
>
> struct timeval tv;
> gettimeofday(&tv, 0);
> long int seed;
> seed = (tv.tv_sec * 1000000) + tv.tv_usec;
>
> // Set the seed
> gen.seed( seed );
>
> I am however not sure how exact it is (high precision timer?!) and if there
> isn't probably a better way to get a fresh seed at every execution. It might
> be that rapid subsequent executions will get the same seed and thus will
> produce the same results.

I use /dev/urandom for this, like so (code fragments):

  FILE *dev_urandom;
  uint32_t seed;
  if((dev_urandom = fopen("/dev/urandom", "r")) == NULL) throw /* error */
  if(fread(&seed, sizeof(seed), 1, dev_urandom) == 0) throw /* error */
  if(fclose(dev_urandom) != 0) throw /* error */
  boost::mt19937 gen(seed);

But maybe there are even better ways.




Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net