mt_rand() 和 rand() 的区别

Difference between mt_rand() and rand()(mt_rand() 和 rand() 的区别)
本文介绍了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_srandsrand 文档.我相信他们会包含更多信息

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() 的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

使用 json_encode对数组加密后,输出的汉字部分是空的,怎么回事了? 各位大侠们,有没有好的解决方案? 急救 解决办法 你原始的数据是gbk的,这是不能被 json_encode 所接受的 json_encode 只接受 utf-8 编码的数据,于是 gbk 汉字因不能识别而丢弃 只有少量
Coalesce function for PHP?(PHP的合并函数?)
Fastest way to convert string to integer in PHP(在 PHP 中将字符串转换为整数的最快方法)
2 Column Mysql Date Range Search in PHP(PHP中的2列Mysql日期范围搜索)
mysql match against ~ example(mysql 匹配 ~ 示例)
How-to: Ranking Search Results(操作方法:对搜索结果进行排名)