search
HomeBackend DevelopmentPHP TutorialDetailed explanation of performance test comparison examples of php function mt_rand() and rand()

The example in this article compares and analyzes the performance issues of random functions mt_rand() and rand() in PHP. Share it with everyone for your reference. The specific analysis is as follows:

In PHP, the mt_rand() and rand() functions can randomly generate a pure number. They both require us to set the seed data and then generate it. Then Which one of mt_rand() and rand() has better performance? Let’s test it with questions.

Example 1. mt_rand() example, the code is as follows:

<?php 
echo mt_rand() . "n"; 
echo mt_rand() . "n"; 
echo mt_rand(5, 15); 
?>

The results are as follows:

1604716014 
1478613278 
6

Note:Since PHP 4.2.0, it is no longer necessary to use the srand() or mt_srand() function to seed the random number generator, it is nowcompleted automatically.

Note:In versions before 3.0.7, max means range. To get the same random number from 5 to 15 as in the above example in these versions, a short example is mt_rand (5, 11).

For details, please refer to the relevant documents of mt_srand(), mt_getrandmax() and rand().

rand() function returns a random integer.

Syntax: rand(min,max)

Parameters Description
min,max Optional, specify the range of random number generation.

说明:如果没有提供可选参数 min 和 max,rand() 返回 0 到 RAND_MAX 之间的伪随机整数,例如,想要 5 到 15(包括 5 和 15)之间的随机数,用 rand(5, 15).

提示和注释

注释:在某些平台下(例如 Windows)RAND_MAX 只有 32768,如果需要的范围大于 32768,那么指定 min 和 max 参数就可以生成大于 RAND_MAX 的数了,或者考虑用 mt_rand() 来替代它.

注释:自 PHP 4.2.0 起,不再需要用 srand() 或 mt_srand() 函数给随机数发生器播种,现在已自动完成.

注释:在 3.0.7 之前的版本中,max 的含义是 range,要在这些版本中得到和上例相同 5 到 15 的随机数,简短的例子是 rand (5, 11).

mt_rand()真的会比rand()快4倍吗?带着这个疑问一边自己测试一边看网上的介绍.测试如下.

mt_rand()和rand()对比测试一,测试代码如下:

<?php  
$max = 100000;  
$timeparts = explode(&#39; &#39;,microtime());  
$stime = $timeparts[1].substr($timeparts[0],1);  
$i = 0;  
while($i < $max) {  
rand();  
$i++;  
}  
$timeparts = explode(&#39; &#39;,microtime());  
$etime = $timeparts[1].substr($timeparts[0],1);  
$time = $etime-$stime;  
echo "{$max} random numbers generated in {$time} seconds using rand();"; 
 
$timeparts = explode(&#39; &#39;,microtime());  
$stime = $timeparts[1].substr($timeparts[0],1);  
$i = 0;  
while($i < $max) {  
mt_rand();  
$i++;  
}  
$timeparts = explode(&#39; &#39;,microtime());  
$etime = $timeparts[1].substr($timeparts[0],1);  
$time = $etime-$stime;  
echo "{$max} random numbers generated in {$time} seconds using mt_rand(); ";  
?>


测试结果如下:
//第一次测试
100000 random numbers generated in 0.024894952774048 seconds using rand();
100000 random numbers generated in 0.028925895690918 seconds using mt_rand();
//第二次测试
100000 random numbers generated in 0.03147292137146 seconds using rand();
100000 random numbers generated in 0.02997088432312 seconds using mt_rand();
//第三次测试
100000 random numbers generated in 0.028102874755859 seconds using rand();
100000 random numbers generated in 0.02803111076355 seconds using mt_rand();
//第四次测试
100000 random numbers generated in 0.025573015213013 seconds using rand();
100000 random numbers generated in 0.028030157089233 seconds using mt_rand();

这个结果只是几次的显示结果,多测试几次你会发觉,两者是交替变化的,其实两者没有太大的差异.

mt_rand()和rand()对比测试二

本人测试环境,操作系统:windows xp,apache 2.0,php 5.2.12,内存 2G

代码如下:

<?php  
function microtime_float()  
{  
    list($usec, $sec) = explode(" ", microtime());  
    return ((float)$usec + (float)$sec);  
}  
$time_start = microtime_float();  
for($i=0; $i<1000000; ++$i)  
{
    rand();  
}  
$time_end = microtime_float();  
$time = $time_end - $time_start;  
echo "rand() cost $time secondsn"; 
 
$time_start = microtime_float();  
for($i=0; $i<1000000; ++$i)  
{  
    mt_rand();  
}  
$time_end = microtime_float();  
$time = $time_end - $time_start;  
echo "mt_rand() cost $time secondsn";  
?>

测试结果如下:
//第一次
rand() cost 0.25919604301453 seconds
mt_rand() cost 0.28554391860962 seconds
//第二次
rand() cost 0.31136202812195 seconds
mt_rand() cost 0.28973197937012 seconds
//第三次
rand() cost 0.27545690536499 seconds
mt_rand() cost 0.27108001708984 seconds
//第四次
rand() cost 0.26263308525085 seconds
mt_rand() cost 0.27727103233337 seconds
结果还是一样:两者用的时间是交替变化,其实两者没有太大的差异.

php的mt_rand()与rand()对比结论

在网上看了很多别人的测试,有linux的还有windows环境的,大多数人得出的结果和我的一样:两者相差无几,不过也有人测出mt_rand()比rand()快4倍,但是由于他们没给出具体的测试环境,所以无法判断真假。我还是比较相信我的结论,因为我看到有人这样介绍mt_rand()与rand():

那为什么php手册上说mt_rand()比rand()快4倍呢?

这是因为mt_rand()使用的Mersenne Twister algorythm是1997的事,所以在10年前,和rand()在速度上的差异是(4倍),自2004年,rand()已经开始使用algorythm,所以现在它们速度上没有太大的区别.

从上面的各种测试来看它们之间并没有区别,只是在不同系统中可能数值会有变化了.


The above is the detailed content of Detailed explanation of performance test comparison examples of php function mt_rand() and rand(). For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

How to make PHP applications fasterHow to make PHP applications fasterMay 12, 2025 am 12:12 AM

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

PHP Performance Optimization Checklist: Improve Speed NowPHP Performance Optimization Checklist: Improve Speed NowMay 12, 2025 am 12:07 AM

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

PHP Dependency Injection: Improve Code TestabilityPHP Dependency Injection: Improve Code TestabilityMay 12, 2025 am 12:03 AM

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

PHP Performance Optimization: Database Query OptimizationPHP Performance Optimization: Database Query OptimizationMay 12, 2025 am 12:02 AM

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor