mt_rand()和rand()之间的区别 [英] Difference between mt_rand() and 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
种子是什么,并使用它可以预测下一个随机数.有一些工具可以执行此操作,因此请使用Google进行一下测试.
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:
这篇关于mt_rand()和rand()之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!