rand vs mt_rand

Not for 'how-to' coding questions but PHP theory instead, this forum is here for those of us who wish to learn about design aspects of programming with PHP.

Moderator: General Moderators

Post Reply
d3ad1ysp0rk
Forum Donator
Posts: 1661
Joined: Mon Oct 20, 2003 8:31 pm
Location: Maine, USA

rand vs mt_rand

Post 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..
User avatar
Weirdan
Moderator
Posts: 5978
Joined: Mon Nov 03, 2003 6:13 pm
Location: Odessa, Ukraine

Post 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.
Post Reply