Home  >  Article  >  Backend Development  >  循环取一个随机数,请教哪种方式更好些

循环取一个随机数,请教哪种方式更好些

WBOY
WBOYOriginal
2016-06-13 12:13:261084browse

循环取一个随机数,请问哪种方式更好些?
for循环18次,每次需要随机得到1,2,3,4中的一个数

<br />$a = floor(18/4);<br />$b = '1,2,3,4';<br />for($i=0;$i<$a;$i++){<br />   $b = $b.',1,2,3,4';<br />}<br />$c = explode(',',$b);<br />for($i=0;$i<18;$i++){<br />   $xuyao = $c[$i];//第1种方式<br />   $xuyao = rand(1,4);//第二种方式<br />   //后续其它代码<br />}<br />

速度+资源占用,请问哪种方式更好些。
------解决思路----------------------
include 'check_speed.php';<br /><br />function f1() {<br />  $a = array(1,2,3,4);<br />  $a = array_merge($a, $a, $a, $a, $a);<br />  shuffle($a);<br />  return join('', array_slice($a, -18));<br />}<br />function f2() {<br />  $r = '';<br />  for($i=0; $i<18; $i++) $r .= rand(1, 4);<br />  return $r;<br />}<br />check_speed(50000, 'f2');<br />check_speed(50000, 'f1');<br />
50000次的平均值
f2<br />时间: 9 微秒<br />内存: 768<br /><br />f1<br />时间: 8 微秒<br />内存: 448<br />

显然 f1 的效率要高于 f2

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