Page 1 of 1

rand vs mt_rand

Posted: Thu Mar 25, 2004 7:47 pm
by d3ad1ysp0rk
According to PHP.net:
Many random number generators of older libcs have dubious or unknown characteristics and are slow. By default, PHP uses the libc random number generator with the rand() function. The mt_rand() function is a drop-in replacement for this. 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.
My tests revealed that the lower number of random numbers you calculate in a script, the less efficient mt_rand() is.

Code: Select all

$start = getmicrotime();
for($i=0;$i<5;$i++){
    $var .= mt_rand(1,100);
}
$end = getmicrotime();
for($i=0;$i<5;$i++){
    $var .= rand(1,100);
}
$end2 = getmicrotime();
$test1 = $end - $start;
$test2 = $end2 - $end;
Change the for loops to 500,000? mt_rand is a few seconds faster
Make it 1million? mt_rand wins again

Make it under 10,000? rand() is more efficient.

Can anyone else test this to see if I'm doing it wrong, or something?
I'm just wondering why it'd be in the manual if it's not true..

Posted: Thu Mar 25, 2004 8:33 pm
by Weirdan
http://www.math.sci.hiroshima-u.ac.jp/~ ... is-mt.html
Fast generation. (Although it depends on the system, it is reported that MT is sometimes faster than the standard ANSI-C library in a system with pipeline and cache memory.) (Note added in 2004/3: on 1998, usually MT was much faster than rand(), but the algorithm for rand() has been substituted, and now there are no much difference in speed.)
Seems like the manual is outdated.