search
HomeBackend DevelopmentPHP Tutorialphp中随机函数mt_rand()与rand()性能对比分析_PHP

本文实例对比分析了php中随机函数mt_rand()与rand()性能问题。分享给大家供大家参考。具体分析如下:

在php中mt_rand()和rand()函数都是可以随机生成一个纯数字的,他们都是需要我们设置好种子数据然后生成,那么mt_rand()和rand()那个性能会好一些呢,下面我们带着疑问来测试一下.

例子1. mt_rand() 范例,代码如下:

代码如下:

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


上例的输出类似于:
 
1604716014
1478613278
6

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

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

详情可查阅 mt_srand(),mt_getrandmax() 和 rand()相关文档.

rand() 函数返回随机整数.

语法:rand(min,max)

参数 描述
min,max 可选,规定随机数产生的范围.

说明:如果没有提供可选参数 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()对比测试一,测试代码如下:

代码如下:

$max = 100000; 
$timeparts = explode(' ',microtime()); 
$stime = $timeparts[1].substr($timeparts[0],1); 
$i = 0; 
while($i rand(); 
$i++; 

$timeparts = explode(' ',microtime()); 
$etime = $timeparts[1].substr($timeparts[0],1); 
$time = $etime-$stime; 
echo "{$max} random numbers generated in {$time} seconds using rand();";
 
$timeparts = explode(' ',microtime()); 
$stime = $timeparts[1].substr($timeparts[0],1); 
$i = 0; 
while($i mt_rand(); 
$i++; 

$timeparts = explode(' ',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

代码如下:

代码如下:

function microtime_float() 

    list($usec, $sec) = explode(" ", microtime()); 
    return ((float)$usec + (float)$sec); 

$time_start = microtime_float(); 
for($i=0; $i {
    rand(); 

$time_end = microtime_float(); 
$time = $time_end - $time_start; 
echo "rand() cost $time secondsn";
 
$time_start = microtime_float(); 
for($i=0; $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,所以现在它们速度上没有太大的区别.

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

希望本文所述对大家的PHP程序设计有所帮助。

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 and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

How does PHP handle object cloning (clone keyword) and the __clone magic method?How does PHP handle object cloning (clone keyword) and the __clone magic method?Apr 17, 2025 am 12:24 AM

In PHP, use the clone keyword to create a copy of the object and customize the cloning behavior through the \_\_clone magic method. 1. Use the clone keyword to make a shallow copy, cloning the object's properties but not the object's properties. 2. The \_\_clone method can deeply copy nested objects to avoid shallow copying problems. 3. Pay attention to avoid circular references and performance problems in cloning, and optimize cloning operations to improve efficiency.

PHP vs. Python: Use Cases and ApplicationsPHP vs. Python: Use Cases and ApplicationsApr 17, 2025 am 12:23 AM

PHP is suitable for web development and content management systems, and Python is suitable for data science, machine learning and automation scripts. 1.PHP performs well in building fast and scalable websites and applications and is commonly used in CMS such as WordPress. 2. Python has performed outstandingly in the fields of data science and machine learning, with rich libraries such as NumPy and TensorFlow.

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool