rand() or mt_rand()... which is better to use?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Citizen
Forum Contributor
Posts: 300
Joined: Wed Jul 20, 2005 10:23 am

rand() or mt_rand()... which is better to use?

Post by Citizen »

In the manual, it appears that both have the exact same funciton, and mt_rand() is advertised as being faster.

Is mt_rand() really faster? Is it *always* better to use?
User avatar
Weirdan
Moderator
Posts: 5978
Joined: Mon Nov 03, 2003 6:13 pm
Location: Odessa, Ukraine

Post by Weirdan »

mt_rand() has predictable characteristics (speed, range of values, distribution) while rand() depends on implementation provided by your operating system (libc)
User avatar
AKA Panama Jack
Forum Regular
Posts: 878
Joined: Mon Nov 14, 2005 4:21 pm

Re: rand() or mt_rand()... which is better to use?

Post by AKA Panama Jack »

Citizen wrote:Is mt_rand() really faster? Is it *always* better to use?
Yes and Yes

We have a browser based game that uses quite a few random numbers and after quite a bit of testing we found that rand() had a bad habit of producing the same number chains even though it reseeds the generator automatically with PHP 4.2 and higher. mt_rand() tended to give a wider range of numbers with far less tendency to repeat patterns.
User avatar
s.dot
Tranquility In Moderation
Posts: 5001
Joined: Sun Feb 06, 2005 7:18 pm
Location: Indiana

Post by s.dot »

If you have multiple requests within a short time period, rand() tends to give out far more repeat numbers.

EDIT| And yes, mt_rand() is faster.
Set Search Time - A google chrome extension. When you search only results from the past year (or set time period) are displayed. Helps tremendously when using new technologies to avoid outdated results.
Z3RO21
Forum Contributor
Posts: 130
Joined: Thu Aug 17, 2006 8:59 am

Post by Z3RO21 »

Yup mt_rand() is faster there was a speed test post done on it (I think it was on this site) and it showed that mt_rand was faster and also had far less repeated characters. Does anyone know what they look like at the c level?
User avatar
xpgeek
Forum Contributor
Posts: 146
Joined: Mon May 22, 2006 1:45 am
Location: Kyiv, Ukraine
Contact:

Post by xpgeek »

Write you own tests for checking productivity of each fucntions.
I suggest write loop on 1 million iteration, but you test may be more specific to you tasks.
Try do it and you would have answers. :wink:
Post Reply