mt rand java,mt_rand()和rand()之间的区别

What is the difference between using mt_rand($min, $max) and rand($min, $max) about the speed?

解决方案

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.

Speed was not why mt_rand was introduced!

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;

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.

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 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

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 was introduced to fix the problems that exist in rand!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值