반응형

1. PHP rand() vs mt_rand()


둘다 PHP 에서 난수를 발생시켜주는 함수입니다. 이름을 보면 알겠지만 당연히 rand() 가 먼저 사용되고 있었구요.


 먼저 기본적인 사용은 rand(), mx_rand() 를 호출하거나 시작값과 끝값을 주어 rand(1,10) , mt_rand(1,10) 과 같이 동일하게 사용하면 됩니다. 


 이렇게 외형적으로는 비슷하나 똑똑한 개발자들이 mt_rand() 를 추가적으로 만든 이유가 있을텐데 그 이유에 대해서 알아보도록 하겠습니다. 앞서 기능을 살펴보면 rand() 와 mt_rand() 는 모두 0부터 시스템에서 제공하는 범위의 난수를 반환하는데(각각 getrandmax(), mt_getrandmax() ), rand() 의 경우엔 운영체제에 따라 max 의 범위가 32,767 이라고 합니다. 따라서 더 큰 수를 사용해야 한다면 mt_rand() 를 사용해야 합니다.


 그리고 내부적인 알고리즘에서 차이가 있습니다. rand() 의 경우에는 LCG(Linear Congruential Generator) 를 사용하고, mt_rand() 는 Mersenne Twister 를 사용합니다. 각각 생성가능한 수의 범위는 다음과 같으며  232  , 219937 − 1  속도 또한 4배나 빠르다고 합니다.


 그래서 아래와 같이 테스트를 해 보았습니다.


<?php

    $mt_rand_start = microtime(true);

    for ($i=0; $i<1000000; $i++)

    {

        $tm_random = mt_rand(0, mt_getrandmax());

    }

    $mt_rand_end = microtime(true);

    $runtimeMtRand= $mt_rand_end - $mt_rand_start;

    echo "Runtime mt_rand(): ".$runtimeMtRand." seconds! \n";


    $rand_start = microtime(true);

    for ($i=0; $i<1000000; $i++)

    {

        $random = rand(0, getrandmax());

    }

    $rand_end = microtime(true);

    $runtimeRand= $rand_end - $rand_start;

    echo "Runtime rand(): ".$runtimeRand." seconds! \n";

?>


결과는... 이론과는 달랐네요. ㅠㅠ 왜?


 실제 사용 시 난수 발생은 rand() 보다 mt_rand() 가 더 확실한 random() 범위를 나타내나 이상하게 속도에서는 앞서거니 뒤서거니 하는 결과를 보였습니다. 인터넷 검색을 해보니 뭐 시스템에 따란 다른 결과를 보이느니 하는데요. 4배까지는 아니더라도 평균적으로 빠른 결과를 보이는 것 같습니다. 



참조>

http://us1.php.net/manual/en/function.rand.php

http://us1.php.net/manual/en/function.mt-rand.php

http://en.wikipedia.org/wiki/Linear_congruential_generator

http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html

http://golearnphp.com/php-rand-vs-mt_rand-and-openssl_random_pseudo_bytes/


반응형

+ Recent posts