29 Dic 2008

PHP: rand() vs. mt_rand()

1

En el capítulo anterior, el blogoamigo Shakaran aconsejó (Gracias!) usar mt_rand(); en lugar de rand();, función que no conocía y al parecer su uso al generar números aleatorios es más recomendable, lo cual fue cierto hasta la nueva implementación de rand();, la cual es más rápida que la mismísima mt_rand();, pero como las palabras se las lleva el viento y teniendo un área de Pruebas (a.k.a. Ejemplos) acá están las evidencias:

Código

<?php
//Función a llamar varias veces
function generarAleatorios($veces=100000)
{
  echo "<h2 style=\"margin-top:20px;\">Se generaron {$veces} (x 2) números aleatorios</h2>";
  $tiempoInicial = microtime(true);
  $i = 0;
  while($i < $veces)
  {
    rand();
    $i++;
  }
  $tiempoFinal = microtime(true);
  $tiempoTotal = $tiempoFinal - $tiempoInicial;
  echo "Fueron <strong>{$tiempoTotal}</strong> segundos usando <strong>rand();</strong><br/>";
 
  $tiempoInicial = microtime(true);
  $i = 0;
  while($i < $veces)
  {
    mt_rand();
    $i++;
  }
  $tiempoFinal = microtime(true);
  $tiempoTotalMt = $tiempoFinal - $tiempoInicial;
  echo "Fueron <strong>{$tiempoTotalMt}</strong> segundos usando <strong>mt_rand();</strong><br/><br/>";
 
  if($tiempoTotal < $tiempoTotalMt)
  {
    $diferencia = $tiempoTotalMt - $tiempoTotal;
    echo "<strong style=\"color:green;\">rand();</strong> fue más rápido por <strong>{$diferencia}</strong> segundos.<br />";
  }
  else if($tiempoTotal > $tiempoTotalMt)
  {
    $direrencia = $tiempoTotal - $tiempoTotalMt;
    echo "<strong style=\"color:red;\">mt_rand();</strong> fue más rápido por <strong>{$diferencia}</strong> segundos.<br />";
  }
  else
  {
    echo "<strong>rand();</strong> y <strong>mt_rand();</strong>, tomaron exactamente el mismo tiempo <strong>{$tiempoTotal}</strong> segundos, increíble!!.<br />";
  }
}
 
//Todo listo!!
//Primero con nuestros 3 números para los colores a ver como van con tan poquitos
generarAleatorios(3);
//Otros números más redondos
generarAleatorios(10000);
generarAleatorios(1000000);
?>

Ejemplo

Puedes ver el código funcionando aquí, así que ahora puedes usar rand(); sin perder anhelados micro-segundos ;)

Referencias

Techno.Dev

  1. shakaran el Diciembre 29, 2008 a las 2:47 pm

    Vaya Evelio, me quito el sombrero ;)

    This is because mt_rand() uses the Mersenne Twister algorythm (1997), so 10 years ago, the speed difference was effective (4 times faster).
    Since 2004 or 2003, don’t remember, the algorythm for rand() has been substituted and now there are no much difference in speed ;)

    A veces no te puedes guiar por la documentación oficial (de donde yo tenia mi referencia) y hacer comprobaciones por uno mismo ;)

    Aunque sean microsegundos, voy a tener que modificar bastantes códigos y algún post de mi blog donde lo aconsejaba.

    Saludos

Deja un comentario

XHTML: Puedes usar estos tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">

Gracias por comentar!!, también te recomiendo el Feed, esta jugoso, sabroso y bajo en grasa... hummmmmm yomi yomi!!