在linux下如何较好的生成随机数

#include <stdlib.h>
#include <errno.h>
#include <iostream>
#include <sys/time.h>

using namespace std;

int main()
{
   int iRandNum = -1;
   const int iRandBeg = 0;
   const int iRandEnd = 9999;

   struct timeval ts;
   struct tm* pstTimeInfo;
   char szTimeBuf[16] = {0};
   char szUniqId[20] ={0};

   /* 
   gettimeofday(&ts, NULL);
   cout << ts.tv_sec << endl;   
   cout << time(0) << endl;  
   注意:该值time(0)返回秒数和ts.tv_sec结果一样。
   */

   for(int i=0;i<10000;i++) {      
       gettimeofday(&ts,NULL);
       pstTimeInfo = localtime((time_t *) &ts.tv_sec);
       strftime(szTimeBuf ,sizeof(szTimeBuf), "%Y%m%d%H%M%S", pstTimeInfo);
 
       //以秒数作为seed生成的随机数效果比较差,重复比较多
       //srand((unsigned int) time(0));

       //gen rand num,这里以微秒作为seed,效果相对好一点,
       //但也存在冲突 srand((unsigned int) ts.tv_usec);

      iRandNum = iRandBeg + (int)((float)(iRandEnd-iRandBeg)*rand()/(RAND_MAX+1.0));
      snprintf(szUniqId, sizeof(szUniqId), "%s%04d", szTimeBuf, iRandNum); 
      cout << szUniqId << endl;
      //usleep(100);
  } //end of for
 }


测试的数据如下:


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值