How to generate a random number from system clock as seed
Joseph Rushton Wakeling
joseph.wakeling at webdrake.net
Sun Jun 9 13:08:01 UTC 2024
On Saturday, 8 June 2024 at 13:19:30 UTC, Eric P626 wrote:
> Now I want to seed the generator using system time.
Just to be clear, do you _specifically_ want to use the system
time, or are you aiming to use the system time to generate
different seeds for each run?
If the latter you might prefer to use the `unpredictableSeed()`
function from `std.random`:
https://dlang.org/phobos/std_random.html#unpredictableSeed
That may use a variety of different methods to generate the seed,
depending on the capabilities of the system, but one of the
fallback options (which is actually the original implementation
IIRC) uses a pseudo-random transformation of values derived from
the thread ID, the process ID, and the current time in ticks as
reported by the system's monotonic clock.
A benefit of that is that it means that different threads in the
same app, and different apps, are guaranteed to get _different_
random seeds if started at the same time.
The preferred alternatives to that use different mechanisms, but
should all have the same desired property of guaranteeing that
different threads get different random seeds.
But FWIW, if current time in ticks is valid for your use-case,
`cast(ulong) MonoTime.currTime.ticks` should do.
Hope that helps!
Best wishes,
-- Joe
More information about the Digitalmars-d-learn
mailing list