Foro de elhacker.net

Programación => PHP => Mensaje iniciado por: madpitbull_99 en 15 Abril 2011, 17:29 pm



Título: Calcular tiempo de ejecución de un script en PHP
Publicado por: madpitbull_99 en 15 Abril 2011, 17:29 pm
Muchas veces en mis proyectos web tengo que optimizar el tiempo de carga y de ejecución de los scripts. Para eso me he creado una pequeña clase muy fácil de utilizar.

Código
  1. <?php
  2.  
  3. /**
  4.  * @author MadPitbull
  5.  * @copyright 2011
  6.  */
  7.  
  8.    class PageLoadingTime{
  9.  
  10.        private $time;
  11.        private $initTime;
  12.        private $finTime;
  13.        private $totalTime;
  14.  
  15.        /**
  16.          * PageLoadingTime::__construct()
  17.          * Starts the timer.
  18.          * @return null
  19.          */
  20.        public function __construct() {
  21.            $this->initPageLoadingTime();
  22.        }
  23.  
  24.        private function initPageLoadingTime() {
  25.            $this->time = microtime();
  26.            $this->time = explode(" ", $this->time);
  27.            $this->time = $this->time[1] + $this->time[0];
  28.            $this->initTime = $this->time;
  29.        }
  30.  
  31.        /**
  32.          * PageLoadingTime::getPageLoadingTime()
  33.          * Returns a float var with the page loading time in micro seconds.
  34.          * @return float
  35.          */
  36.        public function getPageLoadingTime() {
  37.            $this->time =  microtime();
  38.            $this->time = explode(" ", $this->time);
  39.            $this->time = $this->time[1] + $this->time[0];
  40.            $this->finTime = $this->time;
  41.            $this->totalTime = ($this->finTime - $this->initTime);
  42.  
  43.            return $this->totalTime;
  44.        }
  45.  
  46.    }
  47.  
  48. ?>

Su funcionamiento es muy sencillo, utiliza dos timers. El primero es inicializado al invocar al constructor de la clase y el valor del segundo es capturado invocando el método getPageLoadingTime y luego se guarda en otra variable la resta del tiempo registrado al principio del script con el tiempo registrado al final del script.
Os dejo un ejemplo de como funciona y mas abajo un enlace para descargar la clase y el ejemplo.

Código
  1. <?php
  2.  
  3.    include ("class.PageLoadingTime.php");
  4.    echo "[+] Testing the PageLoadingTime PHP Class <br />";
  5.  
  6.    $timer = new PageLoadingTime();
  7.  
  8.    for ($i = 0; $i <= 100; $i++) {
  9.        echo "<p style='text-indent: 1em'>" . $i . "<p>";
  10.    }
  11.  
  12.    echo "<p>Execution time: <b>" . $timer->getPageLoadingTime() . "</b></p>";
  13.  
  14. ?>

El bucle for lo he puesto solo para probar el funcionamiento de la clase.
Os dejo el enlace para descargar la clase, si no queréis descargarla podéis copiarla directamente de aquí, funcionará sin
problemas. [Descargar (http://madhacking-app.googlecode.com/files/classPageLoadingTime.zip)]


Título: Re: Calcular tiempo de ejecución de un script en PHP
Publicado por: WHK en 17 Abril 2011, 07:25 am
está bueno, me gustó, vee si puedes hacer un benchmark y le adjuntas el uso de memoria con memory_get_usage y esas cosas :D


Título: Re: Calcular tiempo de ejecución de un script en PHP
Publicado por: [u]nsigned en 19 Abril 2011, 18:46 pm
Una cosa, por que en lugar de llamar a la funcion initPageLoadingTime desde el contructor, mejor no metes el codigo de dicha fncion dirctamente en el contructor.

Código
  1. public function __construct() {
  2.   $this->time = microtime();
  3.   $this->time = explode(" ", $this->time);
  4.   $this->time = $this->time[1] + $this->time[0];
  5.   $this->initTime = $this->time;
  6. }

Y asi ahorras unos cuantos bytes de memoria  ;D

Saludos