php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #25007 rand & mt_rand seed RNG every call
Submitted: 2003-08-10 18:20 UTC Modified: 2003-08-10 19:43 UTC
From: dcowgill at mail dot communityconnect dot com Assigned: iliaa (profile)
Status: Closed Package: Performance problem
PHP Version: 4.3.3RC3 OS: Linux
Private report: No CVE-ID: None
 [2003-08-10 18:20 UTC] dcowgill at mail dot communityconnect dot com
Description:
------------
From the docs for rand: "In older versions of PHP, you 
had to seed the random number generator before use with 
srand(). Since 4.2.0 this is no longer necessary."

The implication is that rand seeds the RNG the first 
time it is called, unless srand has been previously 
called; however, rand seeds the RNG every time (or 
until srand is explicitly called). This results in a 
significant increase in running time (about an order of 
magnitude).

The above also applies to mt_rand, except that the 
performance penalty is greater (apparently because its 
seed-generation algorithm is more expensive).

(the patch to ext/standard/rand.c to correct the 
problem is trivial)

Reproduce code:
---------------
// t1.php
<?
for ($i=0; $i<100000; $i++) rand(0,10);
?>

// t2.php
<?
srand();
for ($i=0; $i<100000; $i++) rand(0,10);
?>

Actual result:
--------------
$ time php t1.php

real    0m0.729s
user    0m0.650s
sys     0m0.080s

$ time php t2.php

real    0m0.101s
user    0m0.100s
sys     0m0.000s

Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2003-08-10 19:43 UTC] sniper@php.net
This bug has been fixed in CVS.

In case this was a PHP problem, snapshots of the sources are packaged
every three hours; this change will be in the next snapshot. You can
grab the snapshot at http://snaps.php.net/.
 
In case this was a documentation problem, the fix will show up soon at
http://www.php.net/manual/.

In case this was a PHP.net website problem, the change will show
up on the PHP.net site and on the mirror sites in short time.
 
Thank you for the report, and for helping us make PHP better.


 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Thu Nov 21 11:01:29 2024 UTC