php函数mt_rand和rand 速度测试

今天在写代码时,看到以前的同时写了一个取随机数,用到了mt_rand(2,19)

就顺手搜了一下,mt_rand和rand的区别。

先看官方的解释

mt_rand 和 rand

mt_rand — 生成更好的随机数

rand — 产生一个随机整数

 

其实两个函数的功能是没有区别的,都是生成一个随机数字。

从网上拷贝了一个例子,看看两个函数的运行时间。。

<?php
 
function microtime_float()
{
    list($usec, $sec) = explode(" ", microtime());
    return ((float)$usec + (float)$sec);
}
$time_start = microtime_float();
for($i=0; $i<1000000; ++$i)
{
    rand();
}
$time_end = microtime_float();
$time = $time_end - $time_start;
echo "rand() cost $time seconds\n";
-
-                                                                                                                         
$time_start = microtime_float();
for($i=0; $i<1000000; ++$i)
{
    mt_rand();
}
$time_end = microtime_float();
$time = $time_end - $time_start;
echo "mt_rand() cost $time seconds\n";

运行结果:

第一次:
rand() cost 0.14121580123901 seconds
mt_rand() cost 0.11780881881714 seconds
第二次:
rand() cost 0.13028216362 seconds
mt_rand() cost 0.11082696914673 seconds
第三次:
rand() cost 0.12766790390015 seconds
mt_rand() cost 0.10724091529846 seconds

 

可以看到,mt_rand 比 rand的速度快~

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值