Recommended way to initialize srand?

前端 未结 15 1893
夕颜
夕颜 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:51

    The real question you must ask yourself is what randomness quality you need.

    libc random is a LCG

    The quality of randomness will be low whatever input you provide srand with.

    If you simply need to make sure that different instances will have different initializations, you can mix process id (getpid), thread id and a timer. Mix the results with xor. Entropy should be sufficient for most applications.

    Example :

    struct timeb tp;
    ftime(&tp);   
    srand(static_cast(getpid()) ^ 
    static_cast(pthread_self()) ^ 
    static_cast(tp.millitm));
    

    For better random quality, use /dev/urandom. You can make the above code portable in using boost::thread and boost::date_time.

提交回复
热议问题