简体   繁体   English

C ++中的Random()效率

[英]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. 我正在编写需要在1到10之间找到随机数的函数。最简单的方法之一是使用random()libc调用。 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 ? 如果有人对random()的效率有想法,那会有所帮助吗?

Also I notice that random() give the same pattern in 2 runs. 另外我注意到random()在2次运行中给出了相同的模式。

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 第一次输出:-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++ : 其他人已经解释了为什么每次都具有相同的序列,但这是使用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 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()? C的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. 如果您要进行调整,那么如何将rand()的结果拆分为单个数字,以便每次调用获得多个结果。

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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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