Recommended way to initialize srand?

前端 未结 15 1829
夕颜
夕颜 2020-11-22 08:07

I need a \'good\' way to initialize the pseudo-random number generator in C++. I\'ve found an article that states:

In order to generate random-like

15条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-22 08:37

    For those using Visual Studio here's yet another way:

    #include "stdafx.h"
    #include 
    #include  
    
    const __int64 DELTA_EPOCH_IN_MICROSECS= 11644473600000000;
    
    struct timezone2 
    {
      __int32  tz_minuteswest; /* minutes W of Greenwich */
      bool  tz_dsttime;     /* type of dst correction */
    };
    
    struct timeval2 {
    __int32    tv_sec;         /* seconds */
    __int32    tv_usec;        /* microseconds */
    };
    
    int gettimeofday(struct timeval2 *tv/*in*/, struct timezone2 *tz/*in*/)
    {
      FILETIME ft;
      __int64 tmpres = 0;
      TIME_ZONE_INFORMATION tz_winapi;
      int rez = 0;
    
      ZeroMemory(&ft, sizeof(ft));
      ZeroMemory(&tz_winapi, sizeof(tz_winapi));
    
      GetSystemTimeAsFileTime(&ft);
    
      tmpres = ft.dwHighDateTime;
      tmpres <<= 32;
      tmpres |= ft.dwLowDateTime;
    
      /*converting file time to unix epoch*/
      tmpres /= 10;  /*convert into microseconds*/
      tmpres -= DELTA_EPOCH_IN_MICROSECS; 
      tv->tv_sec = (__int32)(tmpres * 0.000001);
      tv->tv_usec = (tmpres % 1000000);
    
    
      //_tzset(),don't work properly, so we use GetTimeZoneInformation
      rez = GetTimeZoneInformation(&tz_winapi);
      tz->tz_dsttime = (rez == 2) ? true : false;
      tz->tz_minuteswest = tz_winapi.Bias + ((rez == 2) ? tz_winapi.DaylightBias : 0);
    
      return 0;
    }
    
    
    int main(int argc, char** argv) {
    
      struct timeval2 tv;
      struct timezone2 tz;
    
      ZeroMemory(&tv, sizeof(tv));
      ZeroMemory(&tz, sizeof(tz));
    
      gettimeofday(&tv, &tz);
    
      unsigned long seed = tv.tv_sec ^ (tv.tv_usec << 12);
    
      srand(seed);
    
    }
    

    Maybe a bit overkill but works well for quick intervals. gettimeofday function found here.

    Edit: upon further investigation rand_s might be a good alternative for Visual Studio, it's not just a safe rand(), it's totally different and doesn't use the seed from srand. I had presumed it was almost identical to rand just "safer".

    To use rand_s just don't forget to #define _CRT_RAND_S before stdlib.h is included.

提交回复
热议问题