开发者

How often should I call srand() in a C++ application?

开发者 https://www.devze.com 2023-03-26 07:08 出处:网络
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开发者_如何

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?


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).


Only once, at the start of your application.


No just calling once is fine. Use the seed value to make the random sequence the same on each execution. This could be useful in making (for example) a game's behaviour deterministic when you replay it for debugging.


call it once when the app starts

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号