Is rand() time-dependent in php?

2020-02-29 02:32发布

问题:

Let we explain what I mean.

Some time ago, while writing a program in c#, I've made following mistake:

int Randomize()
{
    Random r=new Random();
    return  r.Next(0,10);
}

in c#, this is a mistake, because, called several times in a row, this function will return the same value. This is because Random constructor uses time seed, and the time difference between calls was too low (took me an hour to find that one :) ).

Now I'm using rand(...) in php, and I need for the output to always be different, even if 2 scripts are executed at the same time.

Do I have to do something to get this result, or is it designed to work this way?

回答1:

the rand() and also mt_rand() calls srand() and mt_srand() to produce always random results. But here's an interesting post on php.net:

Note that the automatic seeding seems to be done with the current number of seconds which means you can get the same results for several runs on a fast server. Either call srand() yourself with a more frequently changing seed or use mt_rand() which doesn't appear to suffer from the problem.

So, just call srand more frequently or mt_rand.



回答2:

About mt_rand() function...

From http://php.net/manual/en/function.mt-srand.php

As of PHP 4.2.0, there is no need to seed the random number generator with srand() or mt_srand() as this is now done automatically.

(For PHP 5.2.1) The Mersenne Twister implementation in PHP now uses a new seeding algorithm by Richard Wagner. Identical seeds no longer produce the same sequence of values they did in previous versions. This behavior is not expected to change again, but it is considered unsafe to rely upon it nonetheless.

Here is link, with description of the "Mersenne Twister(MT)" pseudorandom number generating algorithm (and implementations in C, C++, C#)

Here you can find implementation of this function in PHP 5

And in php_rand.h I found this:

#ifdef PHP_WIN32
#define GENERATE_SEED() (((long) (time(0) * GetCurrentProcessId())) ^ ((long) (1000000.0 * php_combined_lcg(TSRMLS_C))))
#else
#define GENERATE_SEED() (((long) (time(0) * getpid())) ^ ((long) (1000000.0 * php_combined_lcg(TSRMLS_C))))
#endif

So now you can see, that random functions in PHP relies on time function...



标签: php random