简体   繁体   中英

Random() efficiency in C++

I am writing function where I need to find the random number between 1 - 10. One of the easiest way is to use random() libc call. I am going to use this function a lot. But I don't know how efficient it will be. If any one has idea about efficiency of random() that will be a help ?

Also I notice that random() give the same pattern in 2 runs.

int main()
{
   for(int i=0;i<10;i++)
   {
    cout << random() % 10 << endl;     
   }
}

Output 1st time :- 3 6 7 5 3 5 6 2 9 1

Second time also I got same output.

Then how come it's random ?

Others have explained why it's the same sequence every time, but this is how you generate a random number with C++ :

#include <random>

int main() {
    std::random_device rd{}; //(hopefully) truly random device
    std::mt19937 engine{rd()}; //seed a pseudo rng with random_device
    std::uniform_int_distribution<int> d(1,10); //1 to 10, inclusive
    int RandNum = d(engine); //generate
    return 0;
}

http://en.cppreference.com/w/cpp/numeric/random

The actual execution time depends on your platform of course, but it is pretty much straight forward, couple multiplication and divisions or shifts:

What common algorithms are used for C's rand()?

I don't think you should be worried. If you need a lot of random numbers, then another random source probably would be a better choice for you.

If you are looking for tweaks, how about splitting the result from rand() into individual digits to get several results per call.

This way is very simple and effective, you only need to set the seed:

#include <iostream>
#include <stdlib.h>
#include <time.h>

using namespace std;

int main(){
    srand(time(NULL));
    for(int i=0;i<10;i++)
        cout << rand() % 10 << endl;     
}

要解决在2次运行中获得相同模式的问题,只需添加函数randomize()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM