srand() frequency

How often should someone call srand()? Is it worth it to call it more than once? For example before each call to rand() or after x time.

Thanks for your time
You should only call it once.
I would urge you to consider using <random> if you are using modern C++, or boost::random if you are not, in place of srand()/rand(). They are a little more complex, but they can be used in a thread-safe manner (one generator per thread).
It is an easy replace to use <random> too...

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>

#include <cstdlib>
#include <ctime>

void print_n_random_numbers( int n )
{
  while (n--)
    std::cout << rand() << "\n";
}

int main()
{
  srand( time( nullptr ) );

  print_n_random_numbers( 10 );
}


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>

#include <chrono>
#include <random>

unsigned get_random( unsigned min, unsigned max )
{
  thread_local std::ranlux48 prng( std::chrono::system_clock::now().time_since_epoch().count() );
  std::uniform_int_distribution <unsigned> dist( min, max );
  return dist( prng );
}
unsigned get_random( unsigned range ) { return range ? get_random( 0, range - 1 ) : 0; }
unsigned get_random() { return get_random( 0, ~0U ); }

void print_n_random_numbers( int n )
{
  while (n--)
    std::cout << get_random() << "\n";
}

int main()
{
  print_n_random_numbers( 10 );
}

The C++ version is cleaner and more useful.
Thank you for your answers. I'll give <random> a try.
as a side note, you can use these things as a hash function, reseed off each record's key and get the first value. That will always give you the same value for the same key. This has limited usefulness give <map> but it is occasionally handy if you don't feel like writing a real hash function.

I can't think of any other reason to re-seed for most applications. Only if you want a new stream that you can control (know it will be the same sequence for debugging or other reasons) do you need to re-seed.

Registered users can post here. Sign in or register to post.