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的速度快~

posted @ 2015-09-15 18:29  KoMiles  阅读(1892)  评论(0编辑  收藏  举报