問題描述
使用 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:
這篇關于mt_rand() 和 rand() 的區別的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!