By default, the C random number generator produces the same sequence every time the program is run. In order to generate different sequences, it has to be “seeded” using `srand()`

with a different value each time. The function below to do this is carefully designed. It uses `time()`

to obtain the current time; the alternative `clock()`

is a poor choice because it measures CPU time used, which may vary little from run to run. The actual value of a `time_t`

is not portable, so it computes a “hash” of the bytes in it using a multiply-and-add technique. The factor used for multiplication normally comes out as 257, a prime and therefore a good candidate.

References: Knuth, The Art of Computer Programming, Vol. 2: Seminumerical Algorithms, section 3.2.1; Aho, Sethi, and Ullman, Compilers: Principles, Techniques, and Tools, section 7.6.

#include <limits.h> #include <stdlib.h> #include <time.h> /* Choose and return an initial random seed based on the current time. Based on code by Lawrence Kirby <fred@genesis.demon.co.uk>. Usage: srand (time_seed ()); */ unsigned time_seed (void) { time_t timeval; /* Current time. */ unsigned char *ptr; /* Type punned pointed into timeval. */ unsigned seed; /* Generated seed. */ size_t i; timeval = time (NULL); ptr = (unsigned char *) &timeval; seed = 0; for (i = 0; i < sizeof timeval; i++) seed = seed * (UCHAR_MAX + 2u) + ptr[i]; return seed; }

Last updated 22 Jan 2004 22:59. Copyright © 2004 Ben Pfaff.

May be freely redistributed, but copyright notice must be retained.