mt_rand() was introduced, and it was said to be 4 times faster. The original quote from php.net
It uses a random number generator with known characteristics using the Mersenne Twister, which will produce random numbers four times faster than what the average libc rand() provides.
In Mgccl's machine build with PHP 5.16, Apache 2, 1GB Memory, WinXP SP2, T2500 2.00 GHZ CPU(Intel), this is the result:
Time for mt_rand()0.088899
unrandomness for mt_rand() 194
Time for rand()0.086375
unrandomness for rand()52
Here is the code
$min = "0";
$max = "1";
//Speed For mt_rand()
$i = 0;
$timeparts = explode(' ',microtime());
$starttime = $timeparts[1].substr($timeparts[0],1);
while ($i< 100000){
++$i;
$mt[mt_rand($min, $max)] +=1;
}
$timeparts = explode(' ',microtime());
$endtime = $timeparts[1].substr($timeparts[0],1);
echo 'Time for mt_rand()',bcsub($endtime,$starttime,6),'<br />'; echo 'unrandomness for mt_rand() ',abs($mt[1]-$mt[0]),'<br />';
//Speed For mt_rand()
$i = 0;
$timeparts = explode(' ',microtime());
$starttime = $timeparts[1].substr($timeparts[0],1);
while ($i< 100000){
++$i;
$rand[rand($min, $max)] +=1;
}
$timeparts = explode(' ',microtime());
$endtime = $timeparts[1].substr($timeparts[0],1);
echo 'Time for rand()',bcsub($endtime,$starttime,6),'<br />';
//Note, the less the unrandomness the better
echo 'unrandomness for rand()',abs($rand[1]-$rand[0]),'<br />';
To test the randomness, we can test the unrandomness, if it's randomly choosing between 0 and 1, it will spread out evenly, especially when the times of choosing is great.
unrandomness = absolute value of (times choses 0 - times choses 1)
The smaller the unrandomness value, the better the randomness.
From the result, we can see rand() and mt_rand()'s speed and randomness can vary. In Mgccl's machine, rand() is always faster and more random than mt_rand(). This lead to the conclusion that the server environment determines the speed and randomness of rand() and mt_rand()
Editor Comment:
This is the first time I do benchmark, I might have some mistakes, please point them out.
Recent comments
10 hours 45 min ago
19 hours 58 min ago
2 days 5 hours ago
3 days 9 hours ago
3 days 13 hours ago
3 days 13 hours ago
3 days 13 hours ago
4 days 5 hours ago
4 days 6 hours ago
4 days 8 hours ago