mt_rand() 和 rand() 的区别
使用 mt_rand($min, $max)
和 rand($min, $max)
在速度上有什么区别?
What is the difference between using mt_rand($min, $max)
and rand($min, $max)
about the speed?
推荐答案
更新
自从 PHP 7.1 mt_rand
完全取代了 rand
,并且 rand
成为 mt_rand
的别名.下面的回答主要针对旧版本的两个函数的区别,以及引入mt_rand
的原因.
Update
Since PHP 7.1 mt_rand
has superseded rand
completely, and rand
was made an alias for mt_rand
. The answer below focuses on the differences between the two functions for older versions, and the reasons for introducing mt_rand
.
rand
函数早在 mt_rand
之前就已经存在了,但它有很大的缺陷.PRNG 必须获得一些熵,即生成随机数序列的数字.如果你像这样打印出由 rand()
生成的十个数字的列表:
The rand
function existed way before mt_rand
, but it was deeply flawed. A PRNG must get some entropy, a number from which it generates a sequence of random numbers. If you print out a list of ten numbers that were generated by rand()
like so:
for ($i=0;$i<10;++$i)
echo rand(), PHP_EOL;
输出可用于计算 rand
种子是什么,并用它来预测下一个随机数.有一些工具可以做到这一点,所以谷歌一下并测试一下.
The output can be used to work out what the rand
seed was, and with it, you can predict the next random numbers. There are tools out there that do this, so google a bit and test it.
rand
也存在一个问题,相对快速地显示其随机数中的模式如此处所示.一个问题 mt_rand
似乎也能更好地解决.
There's also an issue with rand
relativily quickly showing patterns in its random numbers as demonstrated here. A problem mt_rand
seems to solve a lot better, too.
mt_rand
使用更好的随机化算法 (Mersenne Twist),它需要在确定种子之前知道更多的随机数并且更快.这并不意味着 mt_rand
根据定义,比 rand
快,这只意味着方式正如此处的其他答案所证明的那样,生成的数字更快,并且似乎对函数的性能没有实际影响.
无论哪种方式,看看mt_srand
和 srand
文档.我相信他们会包含更多信息
mt_rand
uses a better randomization algorithm (Mersenne Twist), which requires more random numbers to be known before the seed can be determined and is faster. This does not mean that mt_rand
is, by definition, faster than rand
is, this only means that the way the numbers are generated is faster, and appears to have no real impact on the function's performance, as other answers here have demonstrated.
Either way, have a look at the mt_srand
and the srand
docs. I'm sure they'll contain some more info
如果 mt_rand
的算法转化为性能的提高,那么这对您来说很好,但这是一个快乐的巧合.TL;TR:
If mt_rand
's algorithm translates in an increase in performance, then that's great for you, but it's a happy coincidence. TL;TR:
相关文章