根据以下结果,使用%
操作生成两个数字之间的均匀随机整数几乎比使用std::uniform_int_distribution
快3倍:是否有充分的理由使用std::uniform_int_distribution
?
代码:
#include <iostream>
#include <functional>
#include <vector>
#include <algorithm>
#include <random>
#include <cstdio>
#include <cstdlib>
using namespace std;
#define N 100000000
int main()
{
clock_t tic,toc;
for(int trials=0; trials<3; trials++)
{
cout<<"trial: "<<trials<<endl;
// uniform_int_distribution
{
int res = 0;
mt19937 gen(1);
uniform_int_distribution<int> dist(0,999);
tic = clock();
for(int i=0; i<N; i++)
{
int r = dist(gen);
res += r;
res %= 1000;
}
toc = clock();
cout << "uniform_int_distribution: "<<(float)(toc-tic)/CLOCKS_PER_SEC << endl;
cout<<res<<" "<<endl;
}
// simple modulus operation
{
int res = 0;
mt19937 gen(1);
tic = clock();
for(int i=0; i<N; i++)
{
int r = gen()%1000;
res += r;
res %= 1000;
}
toc = clock();
cout << "simple modulus operation: "<<(float)(toc-tic)/CLOCKS_PER_SEC << endl;
cout<<res<<" "<<endl;
}
cout<<endl;
}
}
输出:
trial: 0
uniform_int_distribution: 2.90289
538
simple modulus operation: 1.0232
575
trial: 1
uniform_int_distribution: 2.86416
538
simple modulus operation: 1.01866
575
trial: 2
uniform_int_distribution: 2.94309
538
simple modulus operation: 1.01809
575
答案 0 :(得分:40)
当您使用modulo(%
)映射范围时,您将获得统计偏差 rand()
到另一个间隔。
例如,假设rand()
统一(没有偏见)映射到[0, 32767]
,并且您希望映射到[0,4]
rand() % 5
。那么值0,1和2平均将在32768次中产生6554,但值3和4仅产生6553次(因此3 * 6554 + 2 * 6553 = 32768)。
偏差很小(0.01%),但取决于您的应用可能会致命。观看Stephan T. Lavavej的演讲&#34; rand() considered harmful&#34;了解更多详情。