So, I am making a DLL that I want to have a function to generate random numbers. I was wondering which of these options is more efficient (performance wise).
This one is just making a function in a DLL that allows me to get a random number.
int getRand(unsigned int seed) {
int rNum; // Random Number.
srand(seed);
rNum = (rand() % // Whatever I need here.
}
Or, would just using srand(time(nullptr)) and rand() in the application be better in performance?
Thanks,
Johnny P.
There isn’t really any need to create a function that combines a call to
srand()with one torand().srand()is used to seed (i.e. to initialise) a sequence of random numbers. Subsequent, and repeated, calls torand()are then used to actually generate the random numbers. (rand()updates the internal state of the random number generator, so it (generally) won’t generate the same number again when called the next time.)If you call
srand()each time before you callrand(), the sequence will be re-initialised each time. If the seed passed is the same each time, your function will return the same random number each time.Therefore, the two calls will have to be separated anyway.
You may also be interested in the random number generation framework provided by the
<random>header in C++11. Here is example code (mostly copied from cppreference):cppreference has a pretty good description of the
<random>header and the many options it provides: http://en.cppreference.com/w/cpp/numeric/random.Most of this is inspired by the Boost random library, which provides even more options: http://www.boost.org/doc/libs/1_52_0/doc/html/boost_random.html (Link to the 1.52.0 version). Therefore, if you can’t use C++11, or you need functions not provided by the Standard, using the Boost library may be a good idea.