Recommended way to initialize srand?

前端 未结 15 1842
夕颜
夕颜 2020-11-22 08:07

I need a \'good\' way to initialize the pseudo-random number generator in C++. I\'ve found an article that states:

In order to generate random-like

15条回答
  •  臣服心动
    2020-11-22 08:35

    Suppose you have a function with a signature like:

    int foo(char *p);
    

    An excellent source of entropy for a random seed is a hash of the following:

    • Full result of clock_gettime (seconds and nanoseconds) without throwing away the low bits - they're the most valuable.
    • The value of p, cast to uintptr_t.
    • The address of p, cast to uintptr_t.

    At least the third, and possibly also the second, derive entropy from the system's ASLR, if available (the initial stack address, and thus current stack address, is somewhat random).

    I would also avoid using rand/srand entirely, both for the sake of not touching global state, and so you can have more control over the PRNG that's used. But the above procedure is a good (and fairly portable) way to get some decent entropy without a lot of work, regardless of what PRNG you use.

提交回复
热议问题