c++ - What are the advantages of using uniform_int_distribution vs a modulus operation? -
according following results, generating uniform random integers between 2 numbers using %
operation 3 times faster using std::uniform_int_distribution
: there reason use std::uniform_int_distribution
?
code:
#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; } }
output:
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
you statistical bias when use modulo (%
) map range of e.g. rand()
interval.
e.g suppose rand()
maps uniformly (without bias) [0, 32767]
, want map [0,4]
doing rand() % 5
. values 0, 1, , 2 on average produced 6554 out of 32768 times, values 3 , 4 6553 times (so 3 * 6554 + 2 * 6553 = 32768).
the bias small (0.01%) depending on application prove fatal. watch stephan t. lavavej's talk "rand() considered harmful" more details.
Comments
Post a Comment