How often should I call srand() in a C++ application?(在 C++ 应用程序中,我应该多久调用一次 srand()?)
问题描述
我有一个 C++ 应用程序,它在不同的地方调用 rand().我是否需要定期初始化 srand()
以确保 rand() 是合理随机的,还是在应用程序启动时调用一次就足够了?
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?
推荐答案
如果您只有一个线程,请一次.如果您经常重新播种,实际上可能会破坏随机数的某些统计特性.如果您有多个线程,则根本不要使用 rand
,而是使用诸如 drand48_r
之类的线程安全的东西,它可以让您保持每个线程的状态(因此您可以播种一次每个线程).
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).
这篇关于在 C++ 应用程序中,我应该多久调用一次 srand()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 C++ 应用程序中,我应该多久调用一次 srand()?


基础教程推荐
- 这个宏可以转换成函数吗? 2022-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 常量变量在标题中不起作用 2021-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01