Archivo para diciembre 29th, 2008

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