elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.

 

 


Tema destacado: Curso de javascript por TickTack


+  Foro de elhacker.net
|-+  Programación
| |-+  Desarrollo Web
| | |-+  PHP (Moderador: #!drvy)
| | | |-+  Calcular tiempo de ejecución de un script en PHP
0 Usuarios y 1 Visitante están viendo este tema.
Páginas: [1] Ir Abajo Respuesta Imprimir
Autor Tema: Calcular tiempo de ejecución de un script en PHP  (Leído 3,499 veces)
madpitbull_99
Colaborador
***
Desconectado Desconectado

Mensajes: 1.911



Ver Perfil WWW
Calcular tiempo de ejecución de un script en PHP
« 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]


En línea



«Si quieres la paz prepárate para la guerra» Flavius Vegetius

[Taller]Instalación/Configuración y Teoría de Servicios en Red
WHK
Moderador Global
***
Desconectado Desconectado

Mensajes: 6.589


Sin conocimiento no hay espíritu


Ver Perfil WWW
Re: Calcular tiempo de ejecución de un script en PHP
« Respuesta #1 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


En línea

[u]nsigned


Desconectado Desconectado

Mensajes: 2.397

JS/Node developer


Ver Perfil WWW
Re: Calcular tiempo de ejecución de un script en PHP
« Respuesta #2 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

En línea

No hay atajo ante la duda, el misterio se hace aquí...
Se hace carne en cada uno, el misterio es existir!
Páginas: [1] Ir Arriba Respuesta Imprimir 

Ir a:  

Mensajes similares
Asunto Iniciado por Respuestas Vistas Último mensaje
Error ejecución, calcular velocidad de rotación de Satelite.
Java
Noxors 3 5,174 Último mensaje 20 Octubre 2009, 06:19 am
por Leyer
[Script]Script para calcular offset de un ejectuable
Ingeniería Inversa
.:UND3R:. 4 4,727 Último mensaje 29 Septiembre 2011, 16:13 pm
por .:UND3R:.
[Rendimiento] ejecucion de un script por mucho tiempo !??? « 1 2 »
PHP
Diabliyo 10 5,283 Último mensaje 3 Abril 2012, 15:17 pm
por ~ Yoya ~
[Reto Bash] Generar x aleatorios y calcular el tiempo de ejecución.
Scripting
Runex 1 3,280 Último mensaje 28 Marzo 2014, 20:26 pm
por lufalas
[SOLUCIONADO] Calcular el tiempo restante
.NET (C#, VB.NET, ASP)
Eleкtro 2 3,777 Último mensaje 28 Marzo 2013, 05:57 am
por Crazy.sx
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines