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.
<?php
/**
* @author MadPitbull
* @copyright 2011
*/
class PageLoadingTime{
private $time;
private $initTime;
private $finTime;
private $totalTime;
/**
* PageLoadingTime::__construct()
* Starts the timer.
* @return null
*/
public function __construct() {
$this->initPageLoadingTime();
}
private function initPageLoadingTime() {
$this->time = microtime();
$this->time = explode(" ", $this->time);
$this->time = $this->time[1] + $this->time[0];
$this->initTime = $this->time;
}
/**
* PageLoadingTime::getPageLoadingTime()
* Returns a float var with the page loading time in micro seconds.
* @return float
*/
public function getPageLoadingTime() {
$this->time = microtime();
$this->time = explode(" ", $this->time);
$this->time = $this->time[1] + $this->time[0];
$this->finTime = $this->time;
$this->totalTime = ($this->finTime - $this->initTime);
return $this->totalTime;
}
}
?>
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.
<?php
include ("class.PageLoadingTime.php");
echo "[+] Testing the PageLoadingTime PHP Class <br />";
$timer = new PageLoadingTime();
for ($i = 0; $i <= 100; $i++) {
echo "<p style='text-indent: 1em'>" . $i . "<p>";
}
echo "<p>Execution time: <b>" . $timer->getPageLoadingTime() . "</b></p>";
?>
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)]
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
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.
public function __construct() {
$this->time = microtime();
$this->time = explode(" ", $this->time);
$this->time = $this->time[1] + $this->time[0];
$this->initTime = $this->time;
}
Y asi ahorras unos cuantos bytes de memoria ;D
Saludos