How to generate a random number from system clock as seed

Steven Schveighoffer schveiguy at gmail.com
Mon Jun 10 21:07:02 UTC 2024


On Saturday, 8 June 2024 at 13:19:30 UTC, Eric P626 wrote:
> I managed to create a random number generator using the 
> following code:
>
> ~~~
> auto rng = Random(42);
> //....
> uniform(0,10,rng);
> ~~~
>
> Now I want to seed the generator using system time. I looked at 
> Date & time functions/classes and systime functions/classes. 
> The problem is that they all require a time zone. But I don't 
> need a time zone since there is no time zone. I just want the 
> number of seconds elapsed since jan 1st 1970. In other words, 
> the internal system clock value.

I'm not sure if anyone said it explicitly, but `uniform(0, 10)` 
uses the default RNG 
[`rndGen`](https://dlang.org/phobos/std_random.html#rndGen), 
which is already properly seeded with an unpredictable seed:

     Global random number generator used by various functions in 
this module whenever no generator is specified. It is allocated 
per-thread and initialized to an unpredictable value for each 
thread.

So unless you are explicitly doing something like saving the seed 
for future playback, I'd leave it off.

-Steve


More information about the Digitalmars-d-learn mailing list