Recommended way to initialize srand?

2018-12-31 17:01发布

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 numbers, srand is usually initialized to some distinctive value, like those related with the execution time. For example, the value returned by the function time (declared in header ctime) is different each second, which is distinctive enough for most randoming needs.

Unixtime isn't distinctive enough for my application. What's a better way to initialize this? Bonus points if it's portable, but the code will primarily be running on Linux hosts.

I was thinking of doing some pid/unixtime math to get an int, or possibly reading data from /dev/urandom.

Thanks!

EDIT

Yes, I am actually starting my application multiple times a second and I've run into collisions.

标签: c++ random srand
14条回答
人气声优
2楼-- · 2018-12-31 17:24

On windows:

srand(GetTickCount());

provides a better seed than time() since its in milliseconds.

查看更多
深知你不懂我心
3楼-- · 2018-12-31 17:30

Suppose you have a function with a signature like:

int foo(char *p);

An excellent source of entropy for a random seed is a hash of the following:

  • Full result of clock_gettime (seconds and nanoseconds) without throwing away the low bits - they're the most valuable.
  • The value of p, cast to uintptr_t.
  • The address of p, cast to uintptr_t.

At least the third, and possibly also the second, derive entropy from the system's ASLR, if available (the initial stack address, and thus current stack address, is somewhat random).

I would also avoid using rand/srand entirely, both for the sake of not touching global state, and so you can have more control over the PRNG that's used. But the above procedure is a good (and fairly portable) way to get some decent entropy without a lot of work, regardless of what PRNG you use.

查看更多
登录 后发表回答