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

2019-01-20 08:05发布

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?

标签: c++ random srand
4条回答
forever°为你锁心
2楼-- · 2019-01-20 08:44

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.

查看更多
Root(大扎)
3楼-- · 2019-01-20 08:52

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

查看更多
够拽才男人
4楼-- · 2019-01-20 09:00

Only once, at the start of your application.

查看更多
仙女界的扛把子
5楼-- · 2019-01-20 09:05

call it once when the app starts

查看更多
登录 后发表回答