现在的位置: 首页 > 综合 > 正文

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

2013年10月10日 ⁄ 综合 ⁄ 共 815字 ⁄ 字号 评论关闭
#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
 }

测试的数据如下:

抱歉!评论已关闭.