C语言rand(),srand()函数真实性能分析

一直听人说c标准库的rand(), random()随机数产生函数性能极差。一直信以为真,今天做实验,发现并非如此

实验结论如下:

1. 系统自带的rand()和random()函数性能极高,大约相当于2.5次i++

2. rand()函数比random()函数性能稍差,差距大约在10%左右

3. Srand()函数性能非常差,大约比random()函数差了170倍左右,也就是约等于425次i++

4. rand的实现就是简单的乘法和取模,自己实现的随机数在性能上几乎无法超越系统自带的

5. 微软实现的随机数rand()很高效,srand()函数也很高效

实验结果如下图:

C语言rand(),srand()函数真实性能分析_第1张图片

测试代码如下:

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include
using namespace std;

class Random
{
    public:
        static void srandom(int randSeedNum = 321);
        static int random();       
    private:
        static bool         m_bInit;    // 是否已初始化完成
        static int          m_count;    // 计数器
        static vector  m_randSeeds;// 存放随机种子
};

bool Random::m_bInit = false;
int  Random::m_count = 0;
vector  Random::m_randSeeds;
   
// 设置随机种子
void Random::srandom(int randSeedNum)
{
    // 先清空
    m_randSeeds.clear();
    // 再压入0,1,2,3 .... randSeedNum-2
    for(int i=0; i< randSeedNum; ++i){
        m_randSeeds.push_back( i );
    }
    // 打乱
    std::random_shuffle(m_randSeeds.begin(), m_randSeeds.end());
    // 标记已初始化完成
    m_bInit = true;
}

// 返回一个随机数
int Random::random()
{
    // 未初始化,则先初始化
    if(!m_bInit){
        srandom();
    }

    // 随机种子的vector长度
    static int size = m_randSeeds.size();
    
    // 每次自增后,得到随机数
    return 16777619 * m_randSeeds[m_count++%size];
}

// 微软的rand实现(POSIX.1-2001的样例)
static unsigned int next_start = 1;
int randMicro(void)
{
    next_start = next_start * 1103515245 + 12345;
    /* return (unsigned int)(next_start / 65536) % 32768;*/
    return (int)(next_start>>16) & RAND_MAX;
}
void srandMicro(unsigned int seed)
{
     /* And you *should* get a warning if sizes dont match
     */
    next_start = seed;
}

// 变量自增函数
int Inc()
{
    static int iCount = 0;
    return iCount++;
}

// 返回时间间隔,单位:毫秒
int GetPastTime(timeval* pStartTv)
{
    timeval  endTv;
    gettimeofday(&endTv, NULL);
    int uSecond = ((endTv.tv_sec - pStartTv->tv_sec) * 1000000 + endTv.tv_usec - pStartTv->tv_usec)/1000;
    return uSecond;
}

// i++函数1
void TestInc1(int count)
{
    // 起始时间
    timeval startTv;
    gettimeofday(&startTv, NULL);
    
    // 自增count次
    for(int i=0; i>choise;

    switch(choise)
    {
        case 1: // i++函数1
            TestInc1(count);
            break;
        case 2: // i++函数2
            TestInc2(count);
            break;
        case 3: // 系统函数random
            TestMyRandom(count);
            break;
        case 4: // 微软实现的随机数
            TestMicroRandom(count);
            break;
        case 5: // 系统函数random()
            TestRandom(count);
            break;
        case 6: // 系统函数rand()
            TestRand(count);
            break;
        case 7: // 系统函数srand()          
            TestSrand(count);
            break;
        default:
            cout<<"错误的类型"<

 

你可能感兴趣的:(知识积累)