[php] mt_rand and rand

He has: 296 posts

Joined: May 2002

After reading about rand() and mt_rand() I found that mt_rand is supposedly faster a "better random number generator". I did a small benchmark on the speed part and found that rand() is actually faster. I may do a larger benchmark to see the results in larger tests, but the one I did did show rand() was faster.

How I did the benchmark:
I wrote a small script for rand and mt_rand, both exactly the same except the function used. The script generated 1000 random numbers. Each script was run 1000 times, resulting in 1,000,000 random numbers generated for each function. After each test the execution time was inserted into a flat-file (two different ones, one for rand and another for mt_rand). Then an average was calculated and outputed. The result:

rand(): 0.0138205899 Seconds
mt_rand(): 0.0143556833267 Seconds

Granted, the difference isn't THAT large. But if you do generate random numbers alot, it would be nice to know.

Now, there are several things that may effect this. I ran the script on a Windows 2000 machine running PHP 4.3.2 on Apache 2.0.44. All unnesessary programs were shut-down to decrease probability of change in CPU speeds. The machine has a ~450MHZ PII Processor with 256 MB SDRAM.

If anyone thinks I missed something, do tell. This is my first benchmark and its not really exact, just a basic idea.

EDIT:
I just did it where 10,000 random numbers where generated and the scripts where run 1000 times. Results:

rand(): 0.105950111747 Seconds
mt_rand(): 0.112276069045 Seconds

[James Logsdon]

Mark Hensler's picture

He has: 4,048 posts

Joined: Aug 2000

mt_rand() isn't suppose to be faster. It's suppose to generate a number that is closer to a true random number than rand() can.

He has: 296 posts

Joined: May 2002

Hmmm, maybe I shouldn't listen to the User Comments anymore, then?

"...You may also wish to switch to http://php.net/mt_rand which is faster..."

O well, was interesting to do the benchmark (or whatever you want to call it) anyway.

[James Logsdon]

Want to join the discussion? Create an account or log in if you already have one. Joining is fast, free and painless! We’ll even whisk you back here when you’ve finished.