問題描述
我有一個(gè) C++ 應(yīng)用程序,它在不同的地方調(diào)用 rand().我是否需要定期初始化 srand()
以確保 rand() 是合理隨機(jī)的,還是在應(yīng)用程序啟動(dòng)時(shí)調(diào)用一次就足夠了?
I have a C++ application which calls rand() in various places. Do I need to initialize srand()
regularly to ensure that rand() is reasonably random, or is it enough to call it once when the app starts?
推薦答案
如果您只有一個(gè)線程,請(qǐng)一次.如果您經(jīng)常重新播種,實(shí)際上可能會(huì)破壞隨機(jī)數(shù)的某些統(tǒng)計(jì)特性.如果您有多個(gè)線程,則根本不要使用 rand
,而是使用諸如 drand48_r
之類的線程安全的東西,它可以讓您保持每個(gè)線程的狀態(tài)(因此您可以播種一次每個(gè)線程).
If you have only a single thread, seed once. If you reseed often, you might actually break some of the statistical properties of the random numbers. If you have multiple threads, don't use rand
at all, but rather something threadsafe like drand48_r
, which lets you maintain a per-thread state (so you can seed once per thread).
這篇關(guān)于在 C++ 應(yīng)用程序中,我應(yīng)該多久調(diào)用一次 srand()?的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!